You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
GH-55263: [Python][Annotations] Add internal types and core data structures - #55264
This is the next step in adding type annotations to PyArrow (#32609). It merges #49103 (internal type system stubs) and #49193 (core data structures) because the two depend on each other and can't be type checked separately.
What changes are included in this PR?
This PR adds stubs for core data structures and types. Annotations live in pyarrow-stubs/ and can be used at development time. Annotations are not packaged into wheels. Annotations are tested in CI with ci/scripts/python_test_type_annotations.sh and can be linted and tested locally with pre-commit.
During review we agreed on no generics for now (could be follow-up) and overloads are used sparingly.
Detailed AI generated description of changes
**Type stubs** (`python/pyarrow-stubs/`)
Stubs for the parts of pyarrow.lib that hold data types and core data structures: types, array, table, tensor, builder, memory, device, config and error.
pyarrow.types (the is_* predicates, with TypeIs/TypeGuard narrowing).
pyarrow/__init__.pyi now re-exports the annotated public names explicitly, so pa.array, pa.Table, pa.schema etc. are typed.
Placeholders for modules annotated in later PRs: io, ipc, scalar and _compute. Their names resolve to Any, except Buffer and ExtensionScalar, which are empty classes for now. pyarrow/__init__.pyi and lib.pyi also keep a module-level __getattr__ returning Any for names that aren't annotated yet (to be removed before the stubs ship, [CI] Remove all __getattr__(name) -> Any from *.pyi files before next release #48970).
Layout
pyarrow-stubs/ is now laid out as a PEP 561 stub-only package (pyarrow-stubs/__init__.pyi instead of pyarrow-stubs/pyarrow/__init__.pyi), so type checkers and IDEs pick it up from arrow/python.
The stubs for the .pxi files compiled into pyarrow.lib live in a stub-only pyarrow-stubs/__lib/ package and are re-exported from lib.pyi. A flat layout made pa.array, pa.table and pa.scalar resolve to stub modules instead of functions.
Annotation conventions agreed during review
No generics: arrays, scalars and types are not parametrised. Stub-only DataType subclasses in _stubs_typing.pyi describe the results of the type factories.
Return types use Self when the runtime returns the receiver's class and a concrete class otherwise. Parameters never use Self.
Parameters that need an array take the base Array rather than a specific subclass such as BooleanArray or Int32Array, because user variables are usually inferred as Array.
Overloads are used sparingly, only where the un-overloaded annotation would be of little use (for example __getitem__ and asarray).
String options (unit, null_placement, ...) are Literal types, as in NumPy and pandas-stubs.
NumPy arrays are annotated as NDArray[...].
Classes that define __eq__ without __hash__ are marked unhashable.
Type checking setup
mypy, pyright and ty are configured in python/pyproject.toml to check pyarrow-stubs and pyarrow-stubs-tests. Modules that aren't annotated yet are treated as Any.
python/requirements-stubs.txt pins the type checkers and the stub packages of the dependencies. CI and pre-commit both install from it.
New python-stubs pre-commit hooks: ruff lint and format for the .pyi files run on commit; mypy, pyright and ty run on request (pre-commit run --hook-stage manual python-stubs --all-files) and in the Lint CI job.
ci/scripts/python_test_type_annotations.sh now also runs the type stub tests and stubtest against the PyArrow built in CI.
python/scripts/run_stubtest.py runs mypy.stubtest with the __lib modules mapped to pyarrow.lib, using a small allowlist.
Other changes
Small fixes found while reviewing the stubs against the code: docstring corrections in array.pxi, scalar.pxi, tensor.pxi and types.pxi, and comparisons in pyarrow/tests that were missing assert.
# type: ignore comments on the optional-import fallbacks in a few pyarrow/tests files.
Path updates for the new layout in CMakeLists.txt (commented-out install block), python_wheel_validate_contents.py and update_stub_docstrings.py.
The "Type Checking" section of the Python development docs is rewritten.
Are these changes tested?
Yes.
The tests are type checked by mypy, pyright and ty, and run with pytest.
stubtest compares the stub signatures with the installed PyArrow.
The PyArrow test suite (pyarrow/tests) is not type checked in CI yet.
Yes CI runs (ci/scripts/python_test_type_annotations.sh) which in runs typecheckers and tests in python/pyarrow-stubs-tests/.
Changes are also teste locally via pre-commit. Once we package annotations into wheels we should expand testing.
Are there any user-facing changes?
No. The stubs are still not packaged into wheels.
Was AI used for this PR?
In accordance to the AI generation guidelines, please disclose below whether and how AI was used in this PR.
Thanks for continuing to push this forward Rok! I think this PR is a great next step and is quite clear to review.
I have checked out the PR locally and started with running type checkers (mypy, pyright and ty). mypy and ty emit no errors or warnings, but pyright does emit reportMissingImports and reportMissingModuleSource which get fixed with adding _compute.pyi placeholder (similar to existing io.pyi) and reportMissingModuleSource = false under [tool.pyright] in pyproject.toml.
The reason for these warnings and errors in pyright is that locally I have editable pyarrow install where scikit-build-core puts the .so files in a separate folder (not python/pyarrow) without __init__.py and pyright can't find them. As we do not need the compiled modules for the type checkers, I think it is fine to use reportMissingModuleSource = false.
I propose to push the changes directly if we agree the additions makes sense.
Meanwhile I will continue with running the pyarrow-stubs tests.
I have run pytest pyarrow-stubs/tests, no errors found. I have looked through the tests also and tried to break some, everything looks good. I think the tests are easy to follow while still cover a lot of different angles.
I have also run mypy's stubtest with stubtest pyarrow.lib --concise --mypy-config-file pyproject.toml. All of the reported discrepancies are cases of "... is not present in stub" with majority of them being stubs that are not yet included in this PR (scalars, io, etc.). Part of these are also Type_* stubs, for example pyarrow.lib.Type_UINT8. As we already have TypesEnum defined here, might it make sense to also include Type_* stubs now? (I am not inclined towards adding them, just wondering).
Besides the reports mentioned above which will be fixed in subsequent PRs, stubtest did found one bug in pyarrow:
pyarrow.lib.Decima32Array is not present in stub
Note missing "L" in "Decimal". I will work on the fix for this now and would suggest to add it as part of this PR. Can commit directly, if that is ok.
I've run pre-commit run --hook-stage manual python-stubs --all-files which currently uses pyarrow==26.0.0 wheel modules in site-packages/pyarrow, and got all passing (Python Stubs Lint (ruff), Python Stubs Type Check (mypy/pyright/ty)) - except for ruff-format which requires 10 files to be reformatted, fyi @rok Python Stubs Format (ruff)...............................................Failed
Running on editable dev build 27, with pyright==1.1.414 in my conda env, I also hit errors reportMissingImports and warnings reportMissingModuleSource - Suggested changes by @AlenkaF sound good and seem to work fine for me locally.
Thanks for continuing to push this forward Rok! I think this PR is a great next step and is quite clear to review.
I have checked out the PR locally and started with running type checkers (mypy, pyright and ty). mypy and ty emit no errors or warnings, but pyright does emit reportMissingImports and reportMissingModuleSource which get fixed with adding _compute.pyi placeholder (similar to existing io.pyi) and reportMissingModuleSource = false under [tool.pyright] in pyproject.toml.
The reason for these warnings and errors in pyright is that locally I have editable pyarrow install where scikit-build-core puts the .so files in a separate folder (not python/pyarrow) without __init__.py and pyright can't find them. As we do not need the compiled modules for the type checkers, I think it is fine to use reportMissingModuleSource = false.
I propose to push the changes directly if we agree the additions makes sense.
That makes sense and please go for it. I think we should aim for pyproject.toml setting to be as close to the state we want to maintain as possible. So far I've tried to exclude modules that are not covered and ignore as few things as possible. reportMissingModuleSource = false seems good, we will want to challenge it when we have complete coverage.
Part of these are also Type_* stubs, for example pyarrow.lib.Type_UINT8. As we already have TypesEnum defined here, might it make sense to also include Type_* stubs now? (I am not inclined towards adding them, just wondering).
Huh. I've never noticed these were missing. Given we're not really using them as types I'd skip them if we can.
Besides the reports mentioned above which will be fixed in subsequent PRs, stubtest did found one bug in pyarrow:
pyarrow.lib.Decima32Array is not present in stub
Note missing "L" in "Decimal". I will work on the fix for this now and would suggest to add it as part of this PR. Can commit directly, if that is ok.
Huh. Let's do the fix as separate PR, but also include a fix here? (And we'll just rebase over the actual fix on main)
I've run pre-commit run --hook-stage manual python-stubs --all-files which currently uses pyarrow==26.0.0 wheel modules in site-packages/pyarrow, and got all passing (Python Stubs Lint (ruff), Python Stubs Type Check (mypy/pyright/ty)) - except for ruff-format which requires 10 files to be reformatted, fyi @rokPython Stubs Format (ruff)...............................................Failed
I'm not sure we want (can) bring in ruff as a CI dependency. However we should autoformat before we merge, so we don't do it later and change history for no good reason. So I propose one of you runs the ruff formatter and commits the change into this branch.
reportMissingModuleSource = false seems good, we will want to challenge it when we have complete coverage.
I think reportMissingModuleSource will have to stay due to local editable installs. Otherwise I agree, we should ignore as few things as possible.
Will push the commit 👍
Huh. Let's do the fix as separate PR, but also include a fix here? (And we'll just rebase over the actual fix on main)
Sounds good. Will open an issue and a PR and add a fix here also.
Part of these are also Type_* stubs, for example pyarrow.lib.Type_UINT8. As we already have TypesEnum defined here, might it make sense to also include Type_* stubs now? (I am not inclined towards adding them, just wondering).
Huh. I've never noticed these were missing. Given we're not really using them as types I'd skip them if we can.
Yeah, they are internal and exposed through TypesEnum which are added to the stubs here. For stubtest we can later add them to allowlist. For the type checkers we will need to work around them once lib stubs loose their def __getattr__(name: str) -> Any: .... Maybe we can revisit this topic later (maybe we see it's easier to simply add them to the stubs)
... ruff-format which requires 10 files to be reformatted, fyi @rokPython Stubs Format (ruff)...............................................Failed
I'm not sure we want (can) bring in ruff as a CI dependency. However we should autoformat before we merge, so we don't do it later and change history for no good reason. So I propose one of you runs the ruff formatter and commits the change into this branch.
I have started with reviewing pyarrow tests with running mypy --check-untyped-defs --warn-unused-ignores pyarrow/tests/test_* and looking at the ignores. The stubs seem to have changed since the last time type checkers were run on pyarrow tests, example:
Type checkers are currently configured to skip python/pyarrow folder (too much noise) so the changes are not caught. Maybe we could start with adding mypy --check-untyped-defs --warn-unused-ignores pyarrow/tests/test_* for specific files that can already be type checked.
I propose to temporarily add the mypy command explicitly naming files which bypasses the exclude setting to ci/scripts/python_test_type_annotations.sh. Will also push the updates of ignores in the tests once I go through the ones connected to this PR.
Another thing: I can't run pyright on specific files inside an excluded dir. I guess I would need to be running the checks with pyright only locally (with the pyarrow exclude temporarily removed) until the pyarrow/ exclude in pyproject.toml is removed.
Oh, I was too fast here. Unfortunately def __getattr__(name: str) -> Any: ... in python/pyarrow-stubs/pyarrow/__init__.pyi makes anything in form of pa.* be Any making lots of correct ignores (in with pytest.raises ... blocks) falsely reported as unused.
Would it make sense to remove # type: ignores from the pyarrow tests for now and add type checking of the tests (with the ignores) after the stubs are in?
I will leave this for discussion and start with reading the stubs and comparing them with the APIs, starting with _types.pyi first.
Ignore statements not being needed is more likely due to changes to typecheckers than due to changes in stubs. Or they might be needed once we import other parts of the library. Also note camel cased (e.g. reportArgumentType) ignores are likely coming from pyright. So if mypy thinks it's a redundant ignore you might want to check pyright too.
Oh, I was too fast here. Unfortunately def __getattr__(name: str) -> Any: ... in python/pyarrow-stubs/pyarrow/__init__.pyi makes anything in form of pa.* be Any making lots of correct ignores (in with pytest.raises ... blocks) falsely reported as unused.
Would it make sense to remove # type: ignores from the pyarrow tests for now and add type checking of the tests (with the ignores) after the stubs are in?
Let's rather remove def __getattr__(name: str) -> Any: ... at least for development work? Otherwise we'll just need to add ignores again.
OK, agree, when reviewing pyarrow/tests we should remove def __getattr__(name: str) -> Any: ... from python/pyarrow-stubs/pyarrow/__init__.pyi so we keep the ignores and run mypy and pyright (with updated pyproject.toml) so both pass 👍
I plan to do that later and am focusing on reading the stubs currently.
Ehhh... I've fallen into this interesting rabbit hole - There are over 1.5k mypy errors Module not callable in pyarrow/tests because of the change from upstream's zen-xu/pyarrow-stubs having subfolder __lib_pxi to current PR's flat layout without a subfolder (Past discussion rok#45 (comment) was about the naming, but not really why removing subfolder __lib_pxi)
% mypy --check-untyped-defs --warn-unused-ignores pyarrow/tests/test_convert_builtin.py pyarrow/tests/test_convert_builtin.py:78: error: Module not callable [operator]pyarrow/tests/test_convert_builtin.py:79: error: Module not callable [operator]...pyarrow/tests/test_convert_builtin.py:168: error: Module not callable [operator]...Found 321 errors in 1 file (checked 1 source file)
% mypy --check-untyped-defs --warn-unused-ignores pyarrow/tests/test_*.pyFound 1866 errors in 35 files (checked 44 source files)
% ... | grep -c "Module not callable"1562
A stub pyarrow/array.pyi declares pyarrow.array submodule that doesn't exist at runtime because array.pxi gets compiled into lib. Then pa.array, pa.table or pa.scalar can resolve to stub modules instead of functions.
The count of mypy errors may be even higher, depending on module processing order and mypy cache. (optionally run rm -rf .mypy_cache)
So I propose we reintroduce subfolder__lib_pxi/ (or renamed subfolder _lib_pxi/ or just _lib/) in this PR (for files: array.pyi, builder.pyi, config.pyi, device.pyi, error.pyi, io.pyi, memory.pyi, scalar.pyi, table.pyi, tensor.pyi).
Locally that seems to resolve all 1.5k Module not callable errors and still passes type checkers' tests for me.
Just to note: with commit eda3425 stubs array, builder, config, device, error, io, memory, scalar, table, tensor got moved into pyarrow/__lib/ subfolder/subpackage for mypy to not regard pa.array/pa.table/pa.scalar as stub modules anymore and so more than 1500 errors Module not callable in pyarrow/tests no longer show up.
@jorisvandenbossche oh, yes, I think _types.pyi and _ipc.pyi both still need to be moved but there are some extra steps needed (and @AlenkaF has some work in progress on types at the moment, and I may wait for that)
@tadeja@rok I have checked typed.pyi and decided to push a commit (4b97c69) after all =) Instead of suggestions I will post the reasoning behind the changes here:
NumPy is also an optional dependency (next to pandas) so I added # type: ignore[..] there too.
Locally mypy and pyright both pass with only # type: ignore[..] so I removed pyright ignores
ty doesn't honor mypy's # type: ignore[...] and # ty: ignore[unresolved-import] fails if numpy/pandas are installed, so I disabled ty unresolved-import in pyproject.toml instead (mypy and pyright still catch broken imports).
I removed noqa: F401 on the lib import and ruff didn't complain
I have changed some classmethods in stubs as they are defined as static methods in source (types.pxi).
Example: _import_from_c in DataType, Field and Schema.
I propose to use typing_extensions.CapsuleType instead of Any in __arrow_c_schema__.
Claude added a test for this case, I have reviewed and changed it a bit. typing_extensions dependency had to be added.
Note: we should leave the Protocols in _stubs_typing.pyi at Any. Polars' public pl.DataFrame and pl.Series, for example, annotate __arrow_c_stream__ -> object so narrowing the Protocol would reject them
Claude suggested to add a test for Protocols also (under the Table stubs tests, to make sure they do not become to narrow) but I think these should be added later.
I have added overrides to the stubs so they are in sync with runtime and added ignores because of
Return type "Iterator[bytes]" of "keys" incompatible with return type "KeysView[bytes]" in supertype "typing.Mapping" [override]
I have also added a test test_key_value_metadata.
I think code overrides need a separate issue as we might want to decide on changing the overrides in types.pxiKeyValueMetadata class to return Mapping views instead of generators (and to somehow keep support of duplicate keys).
keys_sorted in map_ take bool, None is by truthiness converted to False in Cython but I think it should not be suggested as a possible input so I changed the default from None to False. Same for dictionary().
I have changed the Field methods that returned Self to return Field as the runtime always builds a plain Field via pyarrow_wrap_field.
Future TODO:
string_to_tzinfo, tzinfo_to_string and ensure_metadata are not in the stubs currently (not public). We should add them to the stubtest allowlist at some point or think of adding them to the stubs.
I have run
all 3 type checkers on this file with and without numpy/pandas installed
Only a note on 7fa510f - this is to fix strict type checking errors "Missing type arguments" (np.dtype, list, tuple) and errors due to np.typing.DTypeLike.
...
... Just looked at the specific change for the categories argument in to_pandas (changing categories: list | tuple | None to categories: list[Any] | tuple[Any, ...] | None). Based on the code, I think it should be more correct to use Collection (we iterate and check containment), instead of list/tuple specifically.
(another point here is that, if we add a specific element type, we could probably say the elements should be str instead of Any, since field names are strings (strictly speaking we accept other values, but won't work as expected))
OK, just remembered to post this - verified and fixed to a more suitable Collection[str] with 7e9de7d
Thanks @jorisvandenbossche !
Add a monthly, grouped Dependabot update for the hook revisions in
.pre-commit-config.yaml. clang-format is excluded because bumping it
reformats the codebase.
Add a monthly, grouped Dependabot update for the pins in
python/requirements-stubs.txt. The allow list keeps it away from the
other requirements files in python/.
The reason will be displayed to describe this comment to others. Learn more.
Is it possible to more explicitly "include" just this file? (to avoid having to list all those manually, and also to avoid conflicts. For example, I think we should also pin numpy, but that is also included in some of the other requirements files)
The reason will be displayed to describe this comment to others. Learn more.
A fix on top - 7b75996
I've removed the python/ prefix for exclude-paths as patterns are relative to specified pip's directory: "/python". Also added ignore: for numpy >=2.5, as that would require Python 3.12 but stubs still support 3.11.
Replace the allow list with exclude-paths, so Dependabot reads only
python/requirements-stubs.txt in python/ and any package pinned there
(e.g. numpy) is updated without touching the other requirements files.
The reason will be displayed to describe this comment to others. Learn more.
I think it might be better to pin numpy as well. I think in some earlier comments in the PR thread, it was already mentioned that you get different errors with different versions of numpy (that is also my experience with seeing people maintain the type hints in pandas, that a numpy update typically requires updating some type hints (or ignores) as well)
Numpy will indeed already be installed typically when calling this (from python_test_type_annotations.sh), but then it will just update whatever version is already installed, which is fine?
Which runs on AMD64 Conda Python 3.12 Sphinx Documentation and AMD64 Conda Python 3.12 Sphinx & Numpydoc.
I think this should be it's own CI job separate from documentation. Can we create a follow up issue to run this in a specific annotations CI job instead of running together with docs?
exclude-paths patterns are relative to the directory "/python" specified for pip.
Ignore numpy 2.5+ which requires Python 3.12 while stubs support 3.11.
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Multiple stub signatures diverge from runtime behavior, allowing calls that fail at runtime while rejecting valid mapping inputs and pandas conversion assignments.
No open issues 🎉
5 previously missed issues
In code that hasn't changed since last review
Use receiver-specific return types for to_pandas
python/pyarrow-stubs/__lib/array.pyi:139
Every concrete class inherits this union return type, so even df: pd.DataFrame = pa.table({"a": [1]}).to_pandas() fails type checking, although tables and record batches always return a DataFrame. Conversely, array conversions lose their guaranteed Series result. Please distinguish the return type by receiver, using receiver-specific overloads or concrete-class overrides; this does not require making arrays or tables generic.
Add chunked-input overloads for take, filter, and fill_null
python/pyarrow-stubs/__lib/array.pyi:212
Array.take() returns a ChunkedArray when given chunked indices, so the declared Self return lets calls such as pa.array([1]).take(pa.chunked_array([[0]])).buffers() pass type checking and then fail at runtime. Add overloads distinguishing chunked inputs for take() and filter(); the same return-type mismatch affects fill_null() with a chunked replacement.
Disallow chunked indices in RecordBatch.take
python/pyarrow-stubs/__lib/table.pyi:303
This shared signature also exposes chunked indices on RecordBatch.take, since Indices contains ChunkedArray. However, the runtime's TakeMetaFunction only supports array indices for record batches, so pa.record_batch({'a': [1]}).take(pa.chunked_array([[0]])) is accepted statically but raises ArrowNotImplementedError. Give RecordBatch.take a non-chunked indices signature while retaining chunked-index support for Table.take.
Accept pre-typed string-keyed mappings in schema and struct APIs
python/pyarrow-stubs/__lib/types.pyi:410
Mapping is invariant in its key type, so an ordinary fields: dict[str, pa.DataType] is not assignable to Mapping[str | bytes, ...]. Consequently, valid calls such as pa.schema(fields) and pa.struct(fields) are rejected. The same pattern rejects pre-typed dict[str, str] metadata variables in table.pyi. Please use key-compatible mapping alternatives (as _MetadataMapping already does) and test dictionaries held in variables, not just contextually typed literals.
Make __arrow_array__ type parameter keyword-only
python/pyarrow-stubs/_stubs_typing.pyi:43
The runtime invokes this protocol as obj.__arrow_array__(type=type) (array.pxi:124), so declaring type positional-only reverses the actual contract: positional-only providers satisfy the protocol but raise TypeError in pa.array, while valid keyword-only providers are rejected by type checkers. Declare type keyword-only so structural compatibility matches the runtime call.
The reason will be displayed to describe this comment to others. Learn more.
Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Rationale for this change
This is the next step in adding type annotations to PyArrow (#32609). It merges #49103 (internal type system stubs) and #49193 (core data structures) because the two depend on each other and can't be type checked separately.
What changes are included in this PR?
This PR adds stubs for core data structures and types. Annotations live in
pyarrow-stubs/and can be used at development time. Annotations are not packaged into wheels. Annotations are tested in CI withci/scripts/python_test_type_annotations.shand can be linted and tested locally withpre-commit.During review we agreed on no generics for now (could be follow-up) and overloads are used sparingly.
Detailed AI generated description of changes
**Type stubs** (`python/pyarrow-stubs/`)pyarrow.libthat hold data types and core data structures:types,array,table,tensor,builder,memory,device,configanderror.pyarrow.types(theis_*predicates, withTypeIs/TypeGuardnarrowing).pyarrow/__init__.pyinow re-exports the annotated public names explicitly, sopa.array,pa.Table,pa.schemaetc. are typed.io,ipc,scalarand_compute. Their names resolve toAny, exceptBufferandExtensionScalar, which are empty classes for now.pyarrow/__init__.pyiandlib.pyialso keep a module-level__getattr__returningAnyfor names that aren't annotated yet (to be removed before the stubs ship, [CI] Remove all __getattr__(name) -> Any from *.pyi files before next release #48970).Layout
pyarrow-stubs/is now laid out as a PEP 561 stub-only package (pyarrow-stubs/__init__.pyiinstead ofpyarrow-stubs/pyarrow/__init__.pyi), so type checkers and IDEs pick it up fromarrow/python..pxifiles compiled intopyarrow.liblive in a stub-onlypyarrow-stubs/__lib/package and are re-exported fromlib.pyi. A flat layout madepa.array,pa.tableandpa.scalarresolve to stub modules instead of functions.Annotation conventions agreed during review
DataTypesubclasses in_stubs_typing.pyidescribe the results of the type factories.Selfwhen the runtime returns the receiver's class and a concrete class otherwise. Parameters never useSelf.Arrayrather than a specific subclass such asBooleanArrayorInt32Array, because user variables are usually inferred asArray.pa.array()is annotated as returningArray. The cases where it returns aChunkedArrayare tracked in [Python] Let array() return aChunkedArrayonly when asked #55499.asarray()has overloads.__getitem__andasarray).unit,null_placement, ...) areLiteraltypes, as in NumPy and pandas-stubs.NDArray[...].__eq__without__hash__are marked unhashable.Type checking setup
python/pyproject.tomlto checkpyarrow-stubsandpyarrow-stubs-tests. Modules that aren't annotated yet are treated asAny.python/requirements-stubs.txtpins the type checkers and the stub packages of the dependencies. CI and pre-commit both install from it.python-stubspre-commit hooks: ruff lint and format for the.pyifiles run on commit; mypy, pyright and ty run on request (pre-commit run --hook-stage manual python-stubs --all-files) and in the Lint CI job.ci/scripts/python_test_type_annotations.shnow also runs the type stub tests and stubtest against the PyArrow built in CI.python/scripts/run_stubtest.pyrunsmypy.stubtestwith the__libmodules mapped topyarrow.lib, using a small allowlist.Other changes
array.pxi,scalar.pxi,tensor.pxiandtypes.pxi, and comparisons inpyarrow/teststhat were missingassert.# type: ignorecomments on the optional-import fallbacks in a fewpyarrow/testsfiles.CMakeLists.txt(commented-out install block),python_wheel_validate_contents.pyandupdate_stub_docstrings.py.Are these changes tested?
Yes.
The PyArrow test suite (
pyarrow/tests) is not type checked in CI yet.Yes CI runs (
ci/scripts/python_test_type_annotations.sh) which in runs typecheckers and tests inpython/pyarrow-stubs-tests/.Changes are also teste locally via
pre-commit. Once we package annotations into wheels we should expand testing.Are there any user-facing changes?
No. The stubs are still not packaged into wheels.
Was AI used for this PR?
In accordance to the AI generation guidelines, please disclose below whether and how AI was used in this PR.
PR code and description written by:
Reviewed before submission by: