From 1386fd34102bb814e13e2aa731535225bc31c743 Mon Sep 17 00:00:00 2001 From: Tadeja Kadunc Date: Tue, 17 Nov 2026 23:22:28 +0100 Subject: [PATCH 01/33] Add type annotations for scalars Replace the scalar.pyi placeholder with annotations for Scalar, its subclasses, NA and pyarrow.scalar(), following the conventions of the other stubs: plain classes instead of generics, the class hierarchy of the runtime (e.g. StringScalar is a BinaryScalar, the extension scalars are ExtensionScalars, ListScalar is a Sequence and StructScalar a Mapping), and concrete return types for as_py() and the value properties. Array and ChunkedArray now return real Scalar types from indexing, iteration, sum() and index(), so a ChunkedArray is no longer accepted as the mask of pyarrow.array(). Their __getitem__ gets two overloads, so that an index returns a Scalar and a slice an array, instead of a union of both. Add annotation tests for the scalars. --- python/pyarrow-stubs-tests/test_array.py | 15 +- python/pyarrow-stubs-tests/test_scalar.py | 316 ++++++++++++++++++ python/pyarrow-stubs/__init__.pyi | 53 +++ python/pyarrow-stubs/__lib/array.pyi | 9 +- python/pyarrow-stubs/__lib/scalar.pyi | 377 +++++++++++++++++++++- python/pyarrow-stubs/__lib/table.pyi | 7 +- python/pyproject.toml | 5 +- python/scripts/run_stubtest.py | 12 +- 8 files changed, 770 insertions(+), 24 deletions(-) create mode 100644 python/pyarrow-stubs-tests/test_scalar.py diff --git a/python/pyarrow-stubs-tests/test_array.py b/python/pyarrow-stubs-tests/test_array.py index d64e42779076..f321bdfb247b 100644 --- a/python/pyarrow-stubs-tests/test_array.py +++ b/python/pyarrow-stubs-tests/test_array.py @@ -41,8 +41,8 @@ def test_array() -> None: check(assert_type(arr.null_count, int), int) check(assert_type(len(arr), int), int) check(assert_type(arr.to_pylist(), list[Any]), list) - # Scalars aren't annotated yet, so indexing returns Any, slice keeps the subclass - check(assert_type(arr[0], Any), pa.Int64Scalar) + # Indexing returns a Scalar, slice keeps the subclass + check(assert_type(arr[0], pa.Scalar), pa.Int64Scalar) check(assert_type(arr[1:], pa.Int64Array), pa.Int64Array) # Methods returning the same kind of array keep the subclass. @@ -89,8 +89,9 @@ def test_array_constructors() -> None: if TYPE_CHECKING: pa.array([1, 2], mask=[True, None]) # type: ignore[list-item] - # TODO: when scalars get stubs - # pa.array([1, 2], mask=pa.chunked_array([[True, False]])) + # Chunked arrays aren't accepted as a mask + chunked_mask = pa.chunked_array([[True, False]]) + pa.array([1, 2], mask=chunked_mask) # type: ignore[arg-type] def test_array_operators() -> None: @@ -114,7 +115,7 @@ def test_array_numpy() -> None: import numpy as np arr = cast(pa.Int64Array, pa.array([1, 2])) - check(assert_type(arr[np.int64(0)], Any), pa.Int64Scalar) + check(assert_type(arr[np.int64(0)], pa.Scalar), pa.Int64Scalar) check(assert_type(pa.infer_type(np.array([1])), pa.DataType), pa.DataType) offsets = np.array([0, 1, 2], dtype="int32") check(assert_type(pa.ListArray.from_arrays(offsets, [1, 2]), pa.ListArray), @@ -272,8 +273,8 @@ def test_chunked_array() -> None: check(assert_type(chunked.type, pa.DataType), pa.DataType) check(assert_type(chunked.num_chunks, int), int) check(assert_type(chunked.chunk(0), pa.Array), pa.Int64Array) - # Scalars aren't annotated yet, so indexing returns Any, slice keeps ChunkedArray - check(assert_type(chunked[0], Any), pa.Int64Scalar) + # Indexing returns a Scalar, slice keeps ChunkedArray + check(assert_type(chunked[0], pa.Scalar), pa.Int64Scalar) check(assert_type(chunked[1:], pa.ChunkedArray), pa.ChunkedArray) check(assert_type(chunked.chunks, list[pa.Array]), list) check(assert_type(chunked.combine_chunks(), pa.Array), pa.Int64Array) diff --git a/python/pyarrow-stubs-tests/test_scalar.py b/python/pyarrow-stubs-tests/test_scalar.py new file mode 100644 index 000000000000..be4dc3bdc93a --- /dev/null +++ b/python/pyarrow-stubs-tests/test_scalar.py @@ -0,0 +1,316 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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 datetime as dt +from collections.abc import Hashable, Iterator, Mapping, Sequence +from decimal import Decimal +from typing import Any, cast, TYPE_CHECKING +from uuid import UUID + +import pytest +from typing_extensions import CapsuleType + +import pyarrow as pa +# Not exported from pyarrow until io.pyi is annotated +from pyarrow.lib import Buffer + +from _check import assert_type, check + + +def test_scalar() -> None: + # pa.scalar() return type is Scalar. Tell the type checker which subclass + # to expect. + s = check(assert_type(pa.scalar(1), pa.Scalar), pa.Int64Scalar) + check(assert_type(s.type, pa.DataType), pa.DataType) + check(assert_type(s.is_valid, bool), bool) + check(assert_type(s.as_py(), Any), int) + check(assert_type(s.as_py(maps_as_pydicts="strict"), Any), int) + check(assert_type(s.equals(pa.scalar(1)), bool), bool) + check(assert_type(s.cast(pa.int8()), pa.Scalar), pa.Int8Scalar) + check(assert_type(s.cast("int8", safe=None), pa.Scalar), pa.Int8Scalar) + check(assert_type(pa.scalar(1, "int8"), pa.Scalar), pa.Int8Scalar) + check(assert_type(pa.scalar(1, pa.int8(), from_pandas=True), pa.Scalar), + pa.Int8Scalar) + assert_type(s.validate(full=True), None) + # Scalars, unlike arrays, are hashable + _: Hashable = s + + check(assert_type(pa.NA, pa.NullScalar), pa.NullScalar) + check(assert_type(pa.NULL, pa.NullScalar), pa.NullScalar) + assert_type(pa.NA.as_py(), None) + + +def test_scalar_operators() -> None: + s = pa.scalar(6) + check(assert_type(-s, pa.Scalar), pa.Int64Scalar) + check(assert_type(abs(s), pa.Scalar), pa.Int64Scalar) + # The result is a scalar, or an array if the other operand is one + check(assert_type(s + 1, Any), pa.Int64Scalar) + check(assert_type(s + pa.scalar(1), Any), pa.Int64Scalar) + check(assert_type(s - pa.array([1]), Any), pa.Int64Array) + check(assert_type(s * pa.chunked_array([[1]]), Any), pa.ChunkedArray) + check(assert_type(s / 4, Any), pa.Int64Scalar) + check(assert_type(s ** 2, Any), pa.Int64Scalar) + check(assert_type(s & 3, Any), pa.Int64Scalar) + check(assert_type(s | 3, Any), pa.Int64Scalar) + check(assert_type(s ^ 3, Any), pa.Int64Scalar) + check(assert_type(s << 1, Any), pa.Int64Scalar) + check(assert_type(s >> 1, Any), pa.Int64Scalar) + + if TYPE_CHECKING: + # Scalars don't implement the reflected operators + 1 + s # type: ignore[operator] # ty: ignore[unsupported-operator] + # nor floor division and modulo + s // 2 # type: ignore[operator] # ty: ignore[unsupported-operator] + s % 2 # type: ignore[operator] # ty: ignore[unsupported-operator] + + +def test_array_items() -> None: + arr = cast(pa.Int64Array, pa.array([1, 2])) + check(assert_type(arr[0], pa.Scalar), pa.Int64Scalar) + check(assert_type(next(iter(arr)), pa.Scalar), pa.Int64Scalar) + check(assert_type(arr.sum(), pa.Scalar), pa.Int64Scalar) + check(assert_type(arr.index(2), pa.Int64Scalar), pa.Int64Scalar) + check(assert_type(pa.chunked_array([arr]).index(2), pa.Int64Scalar), + pa.Int64Scalar) + + +def test_primitive_scalars() -> None: + boolean = cast(pa.BooleanScalar, pa.scalar(True)) + check(assert_type(boolean.as_py(), bool | None), bool) + check(assert_type(bool(boolean), bool), bool) + + integer = cast(pa.Int8Scalar, pa.scalar(1, pa.int8())) + check(assert_type(integer.as_py(), int | None), int) + # Integer scalars can be used as indices + check(assert_type([1, 2][integer], int), int) + + double = cast(pa.DoubleScalar, pa.scalar(1.5)) + check(assert_type(double.as_py(), float | None), float) + check(float(double), float) + check(assert_type(int(double), int), int) + + decimal = cast(pa.Decimal128Scalar, pa.scalar(Decimal("1.5"))) + check(assert_type(decimal.as_py(), Decimal | None), Decimal) + + null_int = cast(pa.Int64Scalar, pa.scalar(None, pa.int64())) + assert_type(null_int.as_py(), int | None) + assert null_int.as_py() is None + + +def test_temporal_scalars() -> None: + date = cast(pa.Date32Scalar, pa.scalar(dt.date(2020, 1, 1))) + check(assert_type(date.value, int | None), int) + check(assert_type(date.as_py(), dt.date | None), dt.date) + + date64 = cast(pa.Date64Scalar, pa.scalar(dt.date(2020, 1, 1), pa.date64())) + check(assert_type(date64.value, int | None), int) + check(assert_type(date64.as_py(), dt.date | None), dt.date) + + time = cast(pa.Time64Scalar, pa.scalar(dt.time(1, 2))) + check(assert_type(time.value, int | None), int) + check(assert_type(time.as_py(), dt.time | None), dt.time) + + time32 = cast(pa.Time32Scalar, pa.scalar(dt.time(1, 2), pa.time32("s"))) + check(assert_type(time32.as_py(), dt.time | None), dt.time) + + timestamp = cast(pa.TimestampScalar, pa.scalar(dt.datetime(2020, 1, 1))) + check(assert_type(timestamp.value, int | None), int) + check(assert_type(timestamp.as_py(), dt.datetime | None), dt.datetime) + + duration = cast(pa.DurationScalar, pa.scalar(dt.timedelta(seconds=1))) + check(assert_type(duration.value, int | None), int) + check(assert_type(duration.as_py(), dt.timedelta | None), dt.timedelta) + + interval = cast(pa.MonthDayNanoIntervalScalar, + pa.scalar(pa.MonthDayNano([1, 2, 3]))) + check(assert_type(interval.value, pa.MonthDayNano | None), pa.MonthDayNano) + check(assert_type(interval.as_py(), pa.MonthDayNano | None), + pa.MonthDayNano) + + +def test_binary_scalars() -> None: + binary = cast(pa.BinaryScalar, pa.scalar(b"abc")) + check(assert_type(binary.as_py(), bytes | None), bytes) + check(assert_type(binary.as_buffer(), Buffer | None), pa.Buffer) + check(assert_type(bytes(binary), bytes), bytes) + check(assert_type(memoryview(binary), memoryview), memoryview) + + # String scalars are binary scalars at runtime + string = cast(pa.StringScalar, pa.scalar("abc")) + check(assert_type(string.as_py(), str | None), str) + check(assert_type(string.as_buffer(), Buffer | None), pa.Buffer) + check(string, pa.BinaryScalar) + + large = cast(pa.LargeStringScalar, pa.scalar("abc", pa.large_string())) + check(assert_type(large.as_py(), str | None), str) + view = cast(pa.BinaryViewScalar, pa.scalar(b"abc", pa.binary_view())) + check(assert_type(view.as_py(), bytes | None), bytes) + + +def test_list_scalar() -> None: + lst = cast(pa.ListScalar, pa.scalar([1, 2])) + check(assert_type(lst.values, pa.Array | None), pa.Int64Array) + check(assert_type(len(lst), int), int) + check(assert_type(lst[0], pa.Scalar), pa.Int64Scalar) + check(assert_type(next(iter(lst)), pa.Scalar), pa.Int64Scalar) + check(assert_type(lst.as_py(), list[Any] | None), list) + # List scalars are sequences at runtime + seq: Sequence[pa.Scalar] = check(lst, Sequence) + check(assert_type(seq.index(lst[1]), int), int) + + fixed = cast(pa.FixedSizeListScalar, + pa.scalar([1, 2], pa.list_(pa.int64(), 2))) + check(assert_type(fixed[0], pa.Scalar), pa.Int64Scalar) + + null_list = cast(pa.ListScalar, pa.scalar(None, pa.list_(pa.int64()))) + assert_type(null_list.values, pa.Array | None) + assert null_list.values is None + assert null_list.as_py() is None + + if TYPE_CHECKING: + # Only integer indices are supported, not slices + lst[1:] # type: ignore[index] + + +def test_struct_scalar() -> None: + struct = cast(pa.StructScalar, pa.scalar({"a": 1, "b": "x"})) + check(assert_type(struct["a"], pa.Scalar), pa.Int64Scalar) + check(assert_type(struct[1], pa.Scalar), pa.StringScalar) + check(assert_type(len(struct), int), int) + check(assert_type("a" in struct, bool), bool) + check(assert_type(list(struct), list[str]), list) + check(assert_type(struct.items(), Iterator[tuple[str, pa.Scalar]]), Iterator) + check(assert_type(struct.as_py(), dict[str, Any] | None), dict) + # Struct scalars are mappings at runtime + mapping: Mapping[str, pa.Scalar] = check(struct, Mapping) + check(assert_type(mapping.get("a"), pa.Scalar | None), pa.Int64Scalar) + + +def test_map_scalar() -> None: + map_type = pa.map_(pa.string(), pa.int64()) + map_scalar = cast(pa.MapScalar, pa.scalar([("a", 1)], map_type)) + check(map_scalar, pa.ListScalar) + check(assert_type(map_scalar.values, pa.Array | None), pa.StructArray) + check(assert_type(map_scalar[0], tuple[pa.Scalar, pa.Scalar]), tuple) + check(assert_type(map_scalar["a"], pa.Scalar), pa.Int64Scalar) + check(assert_type(map_scalar.keys(), list[Any]), list) + # Iterating yields the (key, item) pairs as Python objects + check(assert_type(next(iter(map_scalar)), tuple[Any, Any]), tuple) + # as_py() returns a list of pairs, or a dict if maps_as_pydicts is given + check(assert_type(map_scalar.as_py(), list[tuple[Any, Any]] | None), list) + check(assert_type(map_scalar.as_py(maps_as_pydicts="lossy"), + dict[Any, Any] | None), + dict) + + null_map = cast(pa.MapScalar, pa.scalar(None, map_type)) + assert null_map.as_py() is None + assert null_map.as_py(maps_as_pydicts="strict") is None + check(assert_type(null_map.keys(), list[Any]), list) + + +def test_dictionary_scalar() -> None: + dict_arr = pa.array(["a", "b"]).dictionary_encode() + dict_scalar = cast(pa.DictionaryScalar, dict_arr[1]) + index = check(dict_scalar.index, pa.Int32Scalar) + # The index type is one of the integer types + check(assert_type(index.as_py(), int | None), int) + check(assert_type(dict_scalar.value, pa.Scalar), pa.StringScalar) + check(assert_type(dict_scalar.dictionary, pa.Array), pa.StringArray) + + +def test_run_end_encoded_scalar() -> None: + ree = pa.RunEndEncodedArray.from_arrays([2], ["a"]) + ree_scalar = cast(pa.RunEndEncodedScalar, ree[0]) + check(assert_type(ree_scalar.value, pa.Scalar), pa.StringScalar) + + +def test_union_scalar() -> None: + union = pa.UnionArray.from_sparse( + cast(pa.Int8Array, pa.array([0], pa.int8())), [pa.array([1])] + ) + union_scalar = cast(pa.UnionScalar, union[0]) + check(assert_type(union_scalar.value, pa.Scalar | None), pa.Int64Scalar) + check(assert_type(union_scalar.type_code, int), int) + + null_union = pa.UnionArray.from_sparse( + cast(pa.Int8Array, pa.array([0], pa.int8())), + [pa.array([None], pa.int64())], + ) + null_scalar = cast(pa.UnionScalar, null_union[0]) + assert_type(null_scalar.value, pa.Scalar | None) + assert null_scalar.value is None + + +def test_extension_scalars() -> None: + ext = pa.ExtensionScalar.from_storage(pa.uuid(), b"0" * 16) + uuid = check(assert_type(ext, pa.ExtensionScalar), pa.UuidScalar) + check(assert_type(uuid.value, pa.Scalar | None), pa.FixedSizeBinaryScalar) + + uuid_scalar = cast(pa.UuidScalar, uuid) + check(assert_type(uuid_scalar.as_py(), UUID | None), UUID) + + null_uuid = cast(pa.UuidScalar, + pa.ExtensionScalar.from_storage(pa.uuid(), None)) + assert null_uuid.value is None + assert null_uuid.as_py() is None + + bool8 = cast(pa.Bool8Scalar, pa.scalar(1, pa.bool8())) + check(assert_type(bool8.as_py(), bool | None), bool) + + +def test_scalar_numpy_index() -> None: + pytest.importorskip("numpy") + import numpy as np + + # Anything with __index__ can index a list or map scalar, e.g. NumPy ints + lst = cast(pa.ListScalar, pa.scalar([1, 2])) + check(assert_type(lst[np.int64(0)], pa.Scalar), pa.Int64Scalar) + map_scalar = cast(pa.MapScalar, + pa.scalar([("a", 1)], pa.map_(pa.string(), pa.int64()))) + check(assert_type(map_scalar[np.int64(0)], tuple[pa.Scalar, pa.Scalar]), + tuple) + if TYPE_CHECKING: + # Struct scalars only take int positions + struct = cast(pa.StructScalar, pa.scalar({"a": 1})) + struct[np.int64(0)] # type: ignore[index] + + +def test_fixed_shape_tensor_scalar() -> None: + pytest.importorskip("numpy") + import numpy as np + + tensor_type = pa.fixed_shape_tensor(pa.int32(), [2]) + storage = pa.array([[1, 2]], pa.list_(pa.int32(), 2)) + tensors = cast(pa.FixedShapeTensorArray, tensor_type.wrap_array(storage)) + tensor = cast(pa.FixedShapeTensorScalar, tensors[0]) + check(assert_type(tensor.to_numpy(), np.ndarray), np.ndarray) + check(assert_type(tensor.to_tensor(), pa.Tensor), pa.Tensor) + check(assert_type(tensor.__dlpack_device__(), tuple[int, int]), tuple) + check(assert_type(tensor.__dlpack__(max_version=(1, 0)), CapsuleType), + CapsuleType) + + +def test_invalid_usage() -> None: + s = pa.scalar(1) + if TYPE_CHECKING: + s.equals(1) # type: ignore[arg-type] + s.cast(1) # type: ignore[arg-type] + s.as_py(maps_as_pydicts="loose") # type: ignore[arg-type] + pa.scalar(1, type=1) # type: ignore[arg-type] + # Scalars don't have the methods of their subclasses + s.value # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] diff --git a/python/pyarrow-stubs/__init__.pyi b/python/pyarrow-stubs/__init__.pyi index 445936bef98c..d0f4f25f6cf1 100644 --- a/python/pyarrow-stubs/__init__.pyi +++ b/python/pyarrow-stubs/__init__.pyi @@ -35,79 +35,116 @@ from pyarrow.lib import ( ArrowTypeError as ArrowTypeError, BaseExtensionType as BaseExtensionType, BinaryArray as BinaryArray, + BinaryScalar as BinaryScalar, BinaryViewArray as BinaryViewArray, + BinaryViewScalar as BinaryViewScalar, Bool8Array as Bool8Array, + Bool8Scalar as Bool8Scalar, Bool8Type as Bool8Type, BooleanArray as BooleanArray, + BooleanScalar as BooleanScalar, BuildInfo as BuildInfo, ChunkedArray as ChunkedArray, CppBuildInfo as CppBuildInfo, DataType as DataType, Date32Array as Date32Array, + Date32Scalar as Date32Scalar, Date64Array as Date64Array, + Date64Scalar as Date64Scalar, Decimal128Array as Decimal128Array, + Decimal128Scalar as Decimal128Scalar, Decimal128Type as Decimal128Type, Decimal256Array as Decimal256Array, + Decimal256Scalar as Decimal256Scalar, Decimal256Type as Decimal256Type, Decimal32Array as Decimal32Array, + Decimal32Scalar as Decimal32Scalar, Decimal32Type as Decimal32Type, Decimal64Array as Decimal64Array, + Decimal64Scalar as Decimal64Scalar, Decimal64Type as Decimal64Type, DenseUnionType as DenseUnionType, Device as Device, DeviceAllocationType as DeviceAllocationType, DictionaryArray as DictionaryArray, DictionaryMemo as DictionaryMemo, + DictionaryScalar as DictionaryScalar, DictionaryType as DictionaryType, DoubleArray as DoubleArray, + DoubleScalar as DoubleScalar, DurationArray as DurationArray, + DurationScalar as DurationScalar, DurationType as DurationType, ExtensionArray as ExtensionArray, + ExtensionScalar as ExtensionScalar, ExtensionType as ExtensionType, Field as Field, FixedShapeTensorArray as FixedShapeTensorArray, + FixedShapeTensorScalar as FixedShapeTensorScalar, FixedShapeTensorType as FixedShapeTensorType, FixedSizeBinaryArray as FixedSizeBinaryArray, + FixedSizeBinaryScalar as FixedSizeBinaryScalar, FixedSizeBinaryType as FixedSizeBinaryType, FixedSizeListArray as FixedSizeListArray, + FixedSizeListScalar as FixedSizeListScalar, FixedSizeListType as FixedSizeListType, FloatArray as FloatArray, + FloatScalar as FloatScalar, FloatingPointArray as FloatingPointArray, HalfFloatArray as HalfFloatArray, + HalfFloatScalar as HalfFloatScalar, Int16Array as Int16Array, + Int16Scalar as Int16Scalar, Int32Array as Int32Array, + Int32Scalar as Int32Scalar, Int64Array as Int64Array, + Int64Scalar as Int64Scalar, Int8Array as Int8Array, + Int8Scalar as Int8Scalar, IntegerArray as IntegerArray, JsonArray as JsonArray, + JsonScalar as JsonScalar, JsonType as JsonType, KeyValueMetadata as KeyValueMetadata, LargeBinaryArray as LargeBinaryArray, + LargeBinaryScalar as LargeBinaryScalar, LargeListArray as LargeListArray, + LargeListScalar as LargeListScalar, LargeListType as LargeListType, LargeListViewArray as LargeListViewArray, + LargeListViewScalar as LargeListViewScalar, LargeListViewType as LargeListViewType, LargeStringArray as LargeStringArray, + LargeStringScalar as LargeStringScalar, ListArray as ListArray, + ListScalar as ListScalar, ListType as ListType, ListViewArray as ListViewArray, + ListViewScalar as ListViewScalar, ListViewType as ListViewType, LoggingMemoryPool as LoggingMemoryPool, MapArray as MapArray, + MapScalar as MapScalar, MapType as MapType, MemoryManager as MemoryManager, MemoryPool as MemoryPool, MonthDayNano as MonthDayNano, MonthDayNanoIntervalArray as MonthDayNanoIntervalArray, + MonthDayNanoIntervalScalar as MonthDayNanoIntervalScalar, + NA as NA, NullArray as NullArray, + NullScalar as NullScalar, NumericArray as NumericArray, OpaqueArray as OpaqueArray, + OpaqueScalar as OpaqueScalar, OpaqueType as OpaqueType, ProxyMemoryPool as ProxyMemoryPool, RecordBatch as RecordBatch, RunEndEncodedArray as RunEndEncodedArray, + RunEndEncodedScalar as RunEndEncodedScalar, RunEndEncodedType as RunEndEncodedType, RuntimeInfo as RuntimeInfo, + Scalar as Scalar, Schema as Schema, SparseCOOTensor as SparseCOOTensor, SparseCSCMatrix as SparseCSCMatrix, @@ -115,26 +152,38 @@ from pyarrow.lib import ( SparseCSRMatrix as SparseCSRMatrix, SparseUnionType as SparseUnionType, StringArray as StringArray, + StringScalar as StringScalar, StringViewArray as StringViewArray, + StringViewScalar as StringViewScalar, StructArray as StructArray, + StructScalar as StructScalar, StructType as StructType, Table as Table, TableGroupBy as TableGroupBy, Tensor as Tensor, Time32Array as Time32Array, + Time32Scalar as Time32Scalar, Time32Type as Time32Type, Time64Array as Time64Array, + Time64Scalar as Time64Scalar, Time64Type as Time64Type, TimestampArray as TimestampArray, + TimestampScalar as TimestampScalar, TimestampType as TimestampType, UInt16Array as UInt16Array, + UInt16Scalar as UInt16Scalar, UInt32Array as UInt32Array, + UInt32Scalar as UInt32Scalar, UInt64Array as UInt64Array, + UInt64Scalar as UInt64Scalar, UInt8Array as UInt8Array, + UInt8Scalar as UInt8Scalar, UnionArray as UnionArray, + UnionScalar as UnionScalar, UnionType as UnionType, UnknownExtensionType as UnknownExtensionType, UuidArray as UuidArray, + UuidScalar as UuidScalar, UuidType as UuidType, VersionInfo as VersionInfo, array as array, @@ -197,6 +246,7 @@ from pyarrow.lib import ( repeat as repeat, run_end_encoded as run_end_encoded, runtime_info as runtime_info, + scalar as scalar, schema as schema, set_memory_pool as set_memory_pool, set_timezone_db_path as set_timezone_db_path, @@ -225,6 +275,9 @@ from pyarrow.lib import ( from pyarrow import types as types +# pyarrow/__init__.py imports pyarrow.lib._NULL as NULL +NULL: NullScalar + # TODO(GH-48970): remove __getattr__ before release as this # will annotate non-existing attributes as Any. # https://github.com/apache/arrow/issues/48970 diff --git a/python/pyarrow-stubs/__lib/array.pyi b/python/pyarrow-stubs/__lib/array.pyi index d8f97ec67b1b..55a2699f4f6b 100644 --- a/python/pyarrow-stubs/__lib/array.pyi +++ b/python/pyarrow-stubs/__lib/array.pyi @@ -32,9 +32,6 @@ import numpy as np import pandas as pd from numpy.typing import NDArray -# Placeholders (Any) until scalar.pyi is annotated; mypy rejects them as -# types when imported through pyarrow.lib. -from pyarrow.__lib.scalar import Int64Scalar, Scalar from pyarrow._compute import CastOptions from pyarrow._stubs_typing import ( Indices, @@ -56,8 +53,10 @@ from pyarrow.lib import ( Device, DeviceAllocationType, Field, + Int64Scalar, MemoryManager, MemoryPool, + Scalar, Tensor, _Weakrefable, ) @@ -84,9 +83,7 @@ def array( memory_pool: MemoryPool | None = None, ) -> Array: ... @overload -def asarray( # type: ignore[overload-overlap] - values: ChunkedArray, type: Any | None = None -) -> ChunkedArray: ... +def asarray(values: ChunkedArray, type: Any | None = None) -> ChunkedArray: ... @overload def asarray( values: _ArrayConstructorInput, diff --git a/python/pyarrow-stubs/__lib/scalar.pyi b/python/pyarrow-stubs/__lib/scalar.pyi index 307b3e689a25..be4a40d9943e 100644 --- a/python/pyarrow-stubs/__lib/scalar.pyi +++ b/python/pyarrow-stubs/__lib/scalar.pyi @@ -15,11 +15,378 @@ # specific language governing permissions and limitations # under the License. -# Placeholder stub - complete annotations in future PR. -# At runtime, these symbols are provided by the pyarrow.lib C extension. +import datetime as dt +from collections.abc import Iterator, Mapping, Sequence +from decimal import Decimal +from typing import Any, SupportsIndex, TypeAlias, overload +from uuid import UUID -from typing import Any +import numpy as np +from pyarrow._compute import CastOptions +from pyarrow._stubs_typing import MapsAsPydicts +from pyarrow.lib import ( + Array, + BaseExtensionType, + Buffer, + DataType, + MemoryPool, + MonthDayNano, + Tensor, + _Weakrefable, +) +from typing_extensions import CapsuleType -class ExtensionScalar: ... +class Scalar(_Weakrefable): + @property + def type(self) -> DataType: ... + @property + def is_valid(self) -> bool: ... + def cast( + self, + target_type: DataType | str | None = None, + safe: bool | None = None, + options: CastOptions | None = None, + memory_pool: MemoryPool | None = None, + ) -> Scalar: ... + def validate(self, *, full: bool = False) -> None: ... + def equals(self, other: Scalar) -> bool: ... + def as_py(self, *, maps_as_pydicts: MapsAsPydicts | None = None) -> Any: ... + def __abs__(self) -> Scalar: ... + def __neg__(self) -> Scalar: ... + # The binary operators call the compute functions, which return a scalar, + # or an (chunked) array if the other operand is one. + def __add__(self, other: Any, /) -> Any: ... + def __sub__(self, other: Any, /) -> Any: ... + def __mul__(self, other: Any, /) -> Any: ... + def __truediv__(self, other: Any, /) -> Any: ... + def __pow__(self, other: Any, mod: None = None, /) -> Any: ... + def __and__(self, other: Any, /) -> Any: ... + def __or__(self, other: Any, /) -> Any: ... + def __xor__(self, other: Any, /) -> Any: ... + def __lshift__(self, other: Any, /) -> Any: ... + def __rshift__(self, other: Any, /) -> Any: ... -def __getattr__(name: str) -> Any: ... +class NullScalar(Scalar): + def as_py(self, *, maps_as_pydicts: MapsAsPydicts | None = None) -> None: ... + +NA: NullScalar +_NULL: NullScalar + +class BooleanScalar(Scalar): + def as_py(self, *, maps_as_pydicts: MapsAsPydicts | None = None) -> bool | None: ... + def __bool__(self) -> bool: ... + +class UInt8Scalar(Scalar): + def as_py(self, *, maps_as_pydicts: MapsAsPydicts | None = None) -> int | None: ... + def __index__(self) -> int: ... + +class Int8Scalar(Scalar): + def as_py(self, *, maps_as_pydicts: MapsAsPydicts | None = None) -> int | None: ... + def __index__(self) -> int: ... + +class UInt16Scalar(Scalar): + def as_py(self, *, maps_as_pydicts: MapsAsPydicts | None = None) -> int | None: ... + def __index__(self) -> int: ... + +class Int16Scalar(Scalar): + def as_py(self, *, maps_as_pydicts: MapsAsPydicts | None = None) -> int | None: ... + def __index__(self) -> int: ... + +class UInt32Scalar(Scalar): + def as_py(self, *, maps_as_pydicts: MapsAsPydicts | None = None) -> int | None: ... + def __index__(self) -> int: ... + +class Int32Scalar(Scalar): + def as_py(self, *, maps_as_pydicts: MapsAsPydicts | None = None) -> int | None: ... + def __index__(self) -> int: ... + +class UInt64Scalar(Scalar): + def as_py(self, *, maps_as_pydicts: MapsAsPydicts | None = None) -> int | None: ... + def __index__(self) -> int: ... + +class Int64Scalar(Scalar): + def as_py(self, *, maps_as_pydicts: MapsAsPydicts | None = None) -> int | None: ... + def __index__(self) -> int: ... + +_IntegerScalar: TypeAlias = ( + UInt8Scalar + | Int8Scalar + | UInt16Scalar + | Int16Scalar + | UInt32Scalar + | Int32Scalar + | UInt64Scalar + | Int64Scalar +) + +class HalfFloatScalar(Scalar): + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> float | None: ... + def __float__(self) -> float: ... + def __int__(self) -> int: ... + +class FloatScalar(Scalar): + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> float | None: ... + def __float__(self) -> float: ... + def __int__(self) -> int: ... + +class DoubleScalar(Scalar): + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> float | None: ... + def __float__(self) -> float: ... + def __int__(self) -> int: ... + +class Decimal32Scalar(Scalar): + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> Decimal | None: ... + +class Decimal64Scalar(Scalar): + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> Decimal | None: ... + +class Decimal128Scalar(Scalar): + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> Decimal | None: ... + +class Decimal256Scalar(Scalar): + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> Decimal | None: ... + +# The value properties of the temporal scalars hold the integer stored in the +# array (e.g. days since the epoch for Date32Scalar), as_py() converts it. +class Date32Scalar(Scalar): + @property + def value(self) -> int | None: ... + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> dt.date | None: ... + +class Date64Scalar(Scalar): + @property + def value(self) -> int | None: ... + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> dt.date | None: ... + +class Time32Scalar(Scalar): + @property + def value(self) -> int | None: ... + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> dt.time | None: ... + +class Time64Scalar(Scalar): + @property + def value(self) -> int | None: ... + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> dt.time | None: ... + +class TimestampScalar(Scalar): + @property + def value(self) -> int | None: ... + # A pandas.Timestamp, a datetime subclass, for nanoseconds if pandas is + # installed. + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> dt.datetime | None: ... + +class DurationScalar(Scalar): + @property + def value(self) -> int | None: ... + # A pandas.Timedelta, a timedelta subclass, for nanoseconds if pandas is + # installed. + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> dt.timedelta | None: ... + +class MonthDayNanoIntervalScalar(Scalar): + @property + def value(self) -> MonthDayNano | None: ... + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> MonthDayNano | None: ... + +class BinaryScalar(Scalar): + def as_buffer(self) -> Buffer | None: ... + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> bytes | None: ... + def __bytes__(self) -> bytes: ... + # Scalars support the buffer protocol on every Python version, but only + # have a __buffer__ method at runtime from Python 3.12 on. + def __buffer__(self, flags: int, /) -> memoryview: ... + +class LargeBinaryScalar(BinaryScalar): ... +class FixedSizeBinaryScalar(BinaryScalar): ... +class BinaryViewScalar(BinaryScalar): ... + +class StringScalar(BinaryScalar): + def as_py( # type: ignore[override] + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> str | None: ... + +class LargeStringScalar(StringScalar): ... +class StringViewScalar(StringScalar): ... + +class ListScalar(Scalar, Sequence[Scalar]): + @property + def values(self) -> Array | None: ... + def __len__(self) -> int: ... + # Only integer indices, unlike Sequence, which also takes slices. + def __getitem__(self, i: SupportsIndex) -> Scalar: ... # type: ignore[override] + def __iter__(self) -> Iterator[Scalar]: ... + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> list[Any] | None: ... + +class FixedSizeListScalar(ListScalar): ... +class LargeListScalar(ListScalar): ... +class ListViewScalar(ListScalar): ... +class LargeListViewScalar(ListScalar): ... + +class StructScalar(Scalar, Mapping[str, Scalar]): + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[str]: ... + def __contains__(self, key: object, /) -> bool: ... + # Look up a field by name or position. + def __getitem__(self, key: str | bytes | int) -> Scalar: ... + # The runtime yields a generator instead of a Mapping view + def items(self) -> Iterator[tuple[str, Scalar]]: ... # type: ignore[override] + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> dict[str, Any] | None: ... + +# A MapScalar is a list of key-item structs. Unlike a ListScalar, it iterates +# over the (key, item) pairs as Python objects, and can be indexed by key. +class MapScalar(ListScalar): + @overload # type: ignore[override] + def __getitem__(self, i: SupportsIndex) -> tuple[Scalar, Scalar]: ... + @overload + def __getitem__(self, i: str | bytes) -> Scalar: ... + def __iter__(self) -> Iterator[tuple[Any, Any]]: ... # type: ignore[override] + def keys(self) -> list[Any]: ... + # A list of (key, item) tuples, or a dict if maps_as_pydicts is given. + @overload # type: ignore[override] + def as_py( + self, *, maps_as_pydicts: None = None + ) -> list[tuple[Any, Any]] | None: ... + @overload + def as_py(self, *, maps_as_pydicts: MapsAsPydicts) -> dict[Any, Any] | None: ... + +class DictionaryScalar(Scalar): + @property + def index(self) -> _IntegerScalar: ... + @property + def value(self) -> Scalar: ... + @property + def dictionary(self) -> Array: ... + +class RunEndEncodedScalar(Scalar): + @property + def value(self) -> Scalar: ... + +class UnionScalar(Scalar): + @property + def value(self) -> Scalar | None: ... + @property + def type_code(self) -> int: ... + +class ExtensionScalar(Scalar): + @property + def value(self) -> Scalar | None: ... + @staticmethod + def from_storage(typ: BaseExtensionType, value: Any) -> ExtensionScalar: ... + +class JsonScalar(ExtensionScalar): ... + +class UuidScalar(ExtensionScalar): + def as_py(self, *, maps_as_pydicts: MapsAsPydicts | None = None) -> UUID | None: ... + +class FixedShapeTensorScalar(ExtensionScalar): + def to_numpy(self) -> np.ndarray: ... + def to_tensor(self) -> Tensor: ... + def __dlpack__( + self, + *, + stream: int | None = None, + max_version: tuple[int, int] | None = None, + dl_device: tuple[int, int] | None = None, + copy: bool | None = None, + ) -> CapsuleType: ... + def __dlpack_device__(self) -> tuple[int, int]: ... + +class OpaqueScalar(ExtensionScalar): ... + +class Bool8Scalar(ExtensionScalar): + def as_py(self, *, maps_as_pydicts: MapsAsPydicts | None = None) -> bool | None: ... + +def scalar( + value: Any, + type: DataType | str | None = None, + *, + from_pandas: bool | None = None, + memory_pool: MemoryPool | None = None, +) -> Scalar: ... + +__all__ = [ + "Scalar", + "NullScalar", + "NA", + "_NULL", + "BooleanScalar", + "UInt8Scalar", + "Int8Scalar", + "UInt16Scalar", + "Int16Scalar", + "UInt32Scalar", + "Int32Scalar", + "UInt64Scalar", + "Int64Scalar", + "HalfFloatScalar", + "FloatScalar", + "DoubleScalar", + "Decimal32Scalar", + "Decimal64Scalar", + "Decimal128Scalar", + "Decimal256Scalar", + "Date32Scalar", + "Date64Scalar", + "Time32Scalar", + "Time64Scalar", + "TimestampScalar", + "DurationScalar", + "MonthDayNanoIntervalScalar", + "BinaryScalar", + "LargeBinaryScalar", + "FixedSizeBinaryScalar", + "BinaryViewScalar", + "StringScalar", + "LargeStringScalar", + "StringViewScalar", + "ListScalar", + "FixedSizeListScalar", + "LargeListScalar", + "ListViewScalar", + "LargeListViewScalar", + "StructScalar", + "MapScalar", + "DictionaryScalar", + "RunEndEncodedScalar", + "UnionScalar", + "ExtensionScalar", + "JsonScalar", + "UuidScalar", + "FixedShapeTensorScalar", + "OpaqueScalar", + "Bool8Scalar", + "scalar", +] diff --git a/python/pyarrow-stubs/__lib/table.pyi b/python/pyarrow-stubs/__lib/table.pyi index 126a81ce04e3..7b5e51fa7aef 100644 --- a/python/pyarrow-stubs/__lib/table.pyi +++ b/python/pyarrow-stubs/__lib/table.pyi @@ -33,10 +33,9 @@ import numpy as np import pandas as pd from numpy.typing import NDArray -# Placeholders (Any) until ipc.pyi and scalar.pyi are annotated; mypy -# rejects them as types when imported through pyarrow.lib. +# Placeholder (Any) until ipc.pyi is annotated; mypy rejects it as a type +# when imported through pyarrow.lib. from pyarrow.__lib.ipc import RecordBatchReader -from pyarrow.__lib.scalar import Int64Scalar, Scalar from pyarrow._compute import ( CastOptions, CountOptions, @@ -65,8 +64,10 @@ from pyarrow.lib import ( Device, DeviceAllocationType, Field, + Int64Scalar, MemoryManager, MemoryPool, + Scalar, Schema, StructArray, Tensor, diff --git a/python/pyproject.toml b/python/pyproject.toml index b404c261f32f..1556354f6bd7 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -166,9 +166,10 @@ include = ["pyarrow-stubs", "pyarrow-stubs-tests"] # ty doesn't honor `# type: ignore[]` comments, so disable the # rules that those comments suppress for mypy. [[tool.ty.overrides]] -include = ["pyarrow-stubs/__lib/array.pyi"] +include = ["pyarrow-stubs/__lib/array.pyi", "pyarrow-stubs/__lib/scalar.pyi"] [tool.ty.overrides.rules] -# Some array classes override methods with a different signature at runtime. +# Some array and scalar classes override methods with a different signature at +# runtime. incompatible-method-override = "ignore" [[tool.ty.overrides]] diff --git a/python/scripts/run_stubtest.py b/python/scripts/run_stubtest.py index e89e2a6e6db9..a2b853d6750f 100644 --- a/python/scripts/run_stubtest.py +++ b/python/scripts/run_stubtest.py @@ -59,12 +59,22 @@ def main(argv): # and stubtest would check them as if they were stubs. with tempfile.TemporaryDirectory() as tmpdir, contextlib.chdir(tmpdir): os.symlink(STUBS_DIR, Path(tmpdir) / "pyarrow") + allowlists = ["--allowlist", str(ALLOWLIST)] + if sys.version_info < (3, 12): + # Classes that support the buffer protocol only have a __buffer__ + # method from Python 3.12 on (PEP 688), while the stubs declare it + # for every version, like typeshed does. Unused entries fail + # stubtest, so this can't be in the allowlist file. + version_allowlist = Path(tmpdir) / "allowlist.txt" + version_allowlist.write_text( + r"pyarrow\.__lib\.[a-z]+\.[A-Za-z0-9_]+\.__buffer__" "\n") + allowlists += ["--allowlist", str(version_allowlist)] options = stubtest.parse_options([ "pyarrow", "--ignore-missing-stub", # Every Cython extension type is a disjoint base (PEP 800). "--ignore-disjoint-bases", - "--allowlist", str(ALLOWLIST), + *allowlists, "--mypy-config-file", str(PYTHON_DIR / "pyproject.toml"), *argv, ]) From a4b6dda54de09e1d27cfc7b2b631618f27b9e7d7 Mon Sep 17 00:00:00 2001 From: Rok Mihevc Date: Fri, 13 Nov 2026 14:06:32 +0100 Subject: [PATCH 02/33] Add type stubs for the compute and Acero modules Annotate pyarrow.compute, pyarrow._compute, pyarrow._acero and pyarrow._compute_docstrings, following the approach of GH-55264: plain classes and unions instead of generics, in the flat pyarrow-stubs/ layout. - Array arguments accept any Array or ChunkedArray, since pa.array() and most of the API return plain Array instances. The return types name the kind of array where the function determines it. The scalar classes are placeholders (Any) until scalar.pyi is annotated. - The signatures match the runtime, as checked by stubtest. - pyarrow.compute and pyarrow._compute are type checked instead of being treated as Any. - Add type annotation tests for the compute and Acero stubs. --- .pre-commit-config.yaml | 4 +- .../stubtest_allowlist.txt | 1 + python/pyarrow-stubs-tests/test_acero.py | 39 + python/pyarrow-stubs-tests/test_compute.py | 159 ++ python/pyarrow-stubs/_acero.pyi | 116 ++ python/pyarrow-stubs/_compute.pyi | 531 +++++- python/pyarrow-stubs/_compute_docstrings.pyi | 18 + python/pyarrow-stubs/_stubs_typing.pyi | 1 + python/pyarrow-stubs/compute.pyi | 1672 +++++++++++++++++ python/pyproject.toml | 13 +- 10 files changed, 2542 insertions(+), 12 deletions(-) create mode 100644 python/pyarrow-stubs-tests/test_acero.py create mode 100644 python/pyarrow-stubs-tests/test_compute.py create mode 100644 python/pyarrow-stubs/_acero.pyi create mode 100644 python/pyarrow-stubs/_compute_docstrings.pyi create mode 100644 python/pyarrow-stubs/compute.pyi diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index bda8967e30d6..b678fe403b7b 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -150,8 +150,8 @@ repos: # pre-commit run --hook-stage manual python-stubs --all-files # The type checkers run with uvx, in the environment of # python/requirements-stubs.txt. They don't need PyArrow installed: the - # modules that aren't annotated yet, e.g. pyarrow.compute, are treated as Any - # (see python/pyproject.toml). + # modules that aren't annotated yet, e.g. pyarrow.interchange, are treated + # as Any (see python/pyproject.toml). - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.17.2 hooks: diff --git a/python/pyarrow-stubs-tests/stubtest_allowlist.txt b/python/pyarrow-stubs-tests/stubtest_allowlist.txt index b361f3157c92..8346228c95cc 100644 --- a/python/pyarrow-stubs-tests/stubtest_allowlist.txt +++ b/python/pyarrow-stubs-tests/stubtest_allowlist.txt @@ -28,3 +28,4 @@ pyarrow\.__lib\.[a-z]+\.__all__ # The __init__ of Cython extension types takes (*args, **kwargs) at runtime. pyarrow\.__lib\.[a-z]+\.[A-Za-z_]+\.__init__ +pyarrow\._compute\.(Expression|Function|FunctionRegistry|Kernel|UdfContext)\.__init__ diff --git a/python/pyarrow-stubs-tests/test_acero.py b/python/pyarrow-stubs-tests/test_acero.py new file mode 100644 index 000000000000..fe4e9500e9d0 --- /dev/null +++ b/python/pyarrow-stubs-tests/test_acero.py @@ -0,0 +1,39 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from typing import TYPE_CHECKING + +import pytest + +import pyarrow as pa + +from _check import assert_type, check + +# PyArrow can be built without Acero. +pytest.importorskip("pyarrow._acero") + +from pyarrow._acero import Declaration, TableSourceNodeOptions # noqa: E402 + + +def test_declaration() -> None: + table = pa.table({"a": [1, 2]}) + decl = Declaration("table_source", TableSourceNodeOptions(table)) + check(assert_type(decl, Declaration), Declaration) + check(assert_type(decl.to_table(), pa.Table), pa.Table) + + if TYPE_CHECKING: + TableSourceNodeOptions(table.to_batches()[0]) # type: ignore[arg-type] diff --git a/python/pyarrow-stubs-tests/test_compute.py b/python/pyarrow-stubs-tests/test_compute.py new file mode 100644 index 000000000000..2c03b7131d70 --- /dev/null +++ b/python/pyarrow-stubs-tests/test_compute.py @@ -0,0 +1,159 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from collections.abc import Hashable +from types import EllipsisType +from typing import TYPE_CHECKING, TypeAlias + +import pyarrow as pa +import pyarrow.compute as pc +from pyarrow.lib import Buffer + +from _check import assert_type, check + +_Filtered: TypeAlias = ( + pa.Array | pa.ChunkedArray | pa.RecordBatch | pa.Table | pc.Expression +) + + +def test_expression() -> None: + field = pc.field("a") + check(assert_type(field, pc.Expression), pc.Expression) + check(assert_type(pc.field("a", "b"), pc.Expression), pc.Expression) + check(assert_type(pc.field(("a", 0)), pc.Expression), pc.Expression) + check(assert_type(pc.scalar(1), pc.Expression), pc.Expression) + + check(assert_type(field > 1, pc.Expression), pc.Expression) + check(assert_type(field == 1, pc.Expression), pc.Expression) + check(assert_type(field != 1, pc.Expression), pc.Expression) + check(assert_type((field > 1) & (field < 3), pc.Expression), pc.Expression) + check(assert_type(~(field > 1), pc.Expression), pc.Expression) + check(assert_type(field + 1, pc.Expression), pc.Expression) + check(assert_type(field / 2, pc.Expression), pc.Expression) + check(assert_type(field.isin([1, 2]), pc.Expression), pc.Expression) + check(assert_type(field.is_null(nan_is_null=True), pc.Expression), + pc.Expression) + check(assert_type(field.cast(pa.int64()), pc.Expression), pc.Expression) + check(assert_type(field.cast("int64", safe=False), pc.Expression), + pc.Expression) + check(assert_type(field.equals(pc.field("a")), bool), bool) + + # Calling a compute function with an expression builds an expression. + check(pc.count(field), pc.Expression) + check(pc.mean(field), pc.Expression) + + if TYPE_CHECKING: + # Expressions define __eq__ and are unhashable. + _: Hashable = field # type: ignore[assignment] # ty: ignore[invalid-assignment] # noqa: E501 + field.cast(1) # type: ignore[arg-type] + pc.field(1.0) # type: ignore[arg-type] + + +def test_functions() -> None: + func = pc.get_function("sum") + check(assert_type(func, pc.Function), pc.Function) + check(assert_type(func.name, str), str) + check(assert_type(func.arity, int | EllipsisType), int) + check(assert_type(func.num_kernels, int), int) + check(assert_type(pc.list_functions(), list[str]), list) + check(assert_type(pc.function_registry(), pc.FunctionRegistry), + pc.FunctionRegistry) + + +def test_options() -> None: + check(assert_type(pc.CastOptions.safe(pa.int64()), pc.CastOptions), + pc.CastOptions) + check(assert_type(pc.CastOptions.safe().is_safe(), bool), bool) + check(assert_type(pc.ScalarAggregateOptions(skip_nulls=False), + pc.ScalarAggregateOptions), + pc.ScalarAggregateOptions) + check(assert_type(pc.SortOptions([("a", "ascending", "at_start")]), + pc.SortOptions), + pc.SortOptions) + check(assert_type(pc.SelectKOptions(1, [("a", "ascending", "at_end")]), + pc.SelectKOptions), + pc.SelectKOptions) + check(assert_type(pc.SetLookupOptions(pa.chunked_array([[1, 2]])), + pc.SetLookupOptions), + pc.SetLookupOptions) + check(assert_type(pc.RandomOptions(initializer="seed"), pc.RandomOptions), + pc.RandomOptions) + check(assert_type(pc.SearchSortedOptions(side="right"), + pc.SearchSortedOptions), + pc.SearchSortedOptions) + options = pc.RoundOptions(2, round_mode="half_up") + check(assert_type(options.serialize(), Buffer), Buffer) + + if TYPE_CHECKING: + pc.RoundOptions(2, round_mode="nearest") # type: ignore[arg-type] + pc.SearchSortedOptions(side="middle") # type: ignore[arg-type] + _: Hashable = options # type: ignore[assignment] # ty: ignore[invalid-assignment] # noqa: E501 + + +def test_array_functions() -> None: + arr = pa.array([3, 1, 2]) + table = pa.table({"a": [3, 1, 2]}) + + check(assert_type(pc.array_sort_indices(arr), pa.UInt64Array | pc.Expression), + pa.UInt64Array) + check(assert_type(pc.sort_indices(table, [("a", "descending")]), + pa.UInt64Array | pc.Expression), + pa.UInt64Array) + check(assert_type(pc.top_k_unstable(arr, 2), pa.UInt64Array), pa.UInt64Array) + check(assert_type(pc.bottom_k_unstable(table, 2, ["a"], ["at_end"]), + pa.UInt64Array), + pa.UInt64Array) + check(assert_type(pc.indices_nonzero(arr), pa.UInt64Array | pc.Expression), + pa.UInt64Array) + check(assert_type(pc.quantile(arr, q=[0.25, 0.75]), + pa.DoubleArray | pc.Expression), + pa.DoubleArray) + check(assert_type(pc.mode(arr, n=2), pa.StructArray | pc.Expression), + pa.StructArray) + check(assert_type(pc.value_counts(arr), pa.StructArray | pc.Expression), + pa.StructArray) + check(assert_type(pc.random(3), pa.DoubleArray), pa.DoubleArray) + + mask = pa.array([True, False, True]) + check(assert_type(pc.filter(table, mask), _Filtered), pa.Table) + check(assert_type(pc.drop_null(table), _Filtered), pa.Table) + check(assert_type(pc.filter(pc.field("a"), pc.field("b")), + _Filtered), + pc.Expression) + + # Python lists and other iterables are accepted where the stubs list them. + check(pc.round((1.5, 2.5)), pa.Array) + check(pc.first_last((1, 2)), pa.StructScalar) + check(pc.binary_repeat(pa.array(["a"]), (2,)), pa.Array) + check(pc.struct_field(pa.array([{"a": 1}]), ("a",)), pa.Array) + check(assert_type(pc.partition_nth_indices([3, 1, 2], pivot=1), + pa.UInt64Array | pc.Expression), + pa.UInt64Array) + check(pc.round([1.5, 2.5]), pa.Array) + check(pc.binary_join_element_wise(["a", "b"], ["c", "d"], "-"), pa.Array) + + # Python literals are accepted next to arrays. + check(pc.power(arr, 2), pa.Array) + check(pc.divide(arr, 2.0), pa.Array) + + taken = pc.take(arr, [0, 2]) + check(assert_type(taken, pa.Array | pa.ChunkedArray | pa.RecordBatch | pa.Table), + pa.Array) + + if TYPE_CHECKING: + pc.top_k_unstable(arr, "2") # type: ignore[arg-type] + pc.sort_indices(table, [("a", "up")]) # type: ignore[list-item] diff --git a/python/pyarrow-stubs/_acero.pyi b/python/pyarrow-stubs/_acero.pyi new file mode 100644 index 000000000000..ca36550662f4 --- /dev/null +++ b/python/pyarrow-stubs/_acero.pyi @@ -0,0 +1,116 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from collections.abc import Collection, Iterable, Sequence +from typing import Literal, TypeAlias + +# Placeholder (Any) until ipc.pyi is annotated; mypy rejects it as a type +# when imported through pyarrow.lib. +from pyarrow.__lib.ipc import RecordBatchReader +from pyarrow.__lib.table import _AggregateOptions, _AggregationName +from pyarrow._stubs_typing import NullPlacement, Order +from pyarrow.lib import Table, _Weakrefable + +from pyarrow.compute import Expression + +_StrOrExpr: TypeAlias = str | Expression +_IntoField: TypeAlias = str | int | Expression +_Target: TypeAlias = _IntoField | tuple[_IntoField, ...] | Sequence[_IntoField] +_Aggregate: TypeAlias = tuple[_Target, _AggregationName, _AggregateOptions | None, str] +_SortKey: TypeAlias = ( + tuple[str | Expression | int, Order] + | tuple[str | Expression | int, Order, NullPlacement] +) +_JoinType: TypeAlias = Literal[ + "left semi", + "right semi", + "left anti", + "right anti", + "inner", + "left outer", + "right outer", + "full outer", +] + +class Declaration(_Weakrefable): + def __init__( + self, + factory_name: str, + options: ExecNodeOptions, + inputs: list[Declaration] | None = None, + ) -> None: ... + @staticmethod + def from_sequence(decls: Iterable[Declaration]) -> Declaration: ... + def to_reader(self, use_threads: bool = True) -> RecordBatchReader: ... + def to_table(self, use_threads: bool = True) -> Table: ... + +class ExecNodeOptions(_Weakrefable): ... + +class TableSourceNodeOptions(ExecNodeOptions): + def __init__(self, table: Table) -> None: ... + +class RecordBatchReaderSourceNodeOptions(ExecNodeOptions): + def __init__(self, reader: RecordBatchReader) -> None: ... + +class FilterNodeOptions(ExecNodeOptions): + def __init__(self, filter_expression: Expression) -> None: ... + +class ProjectNodeOptions(ExecNodeOptions): + def __init__( + self, + expressions: Collection[Expression], + names: Collection[str] | None = None, + ) -> None: ... + +class AggregateNodeOptions(ExecNodeOptions): + def __init__( + self, + aggregates: Iterable[_Aggregate], + keys: Iterable[str | Expression] | None = None, + ) -> None: ... + +class OrderByNodeOptions(ExecNodeOptions): + def __init__( + self, + sort_keys: Iterable[_SortKey] = (), + *, + # Deprecated: specify the null placement per sort key instead. + null_placement: NullPlacement | None = None, + ) -> None: ... + +class HashJoinNodeOptions(ExecNodeOptions): + def __init__( + self, + join_type: _JoinType, + left_keys: _StrOrExpr | Sequence[_StrOrExpr], + right_keys: _StrOrExpr | Sequence[_StrOrExpr], + left_output: Sequence[_StrOrExpr] | None = None, + right_output: Sequence[_StrOrExpr] | None = None, + output_suffix_for_left: str = "", + output_suffix_for_right: str = "", + filter_expression: Expression | None = None, + ) -> None: ... + +class AsofJoinNodeOptions(ExecNodeOptions): + def __init__( + self, + left_on: _StrOrExpr, + left_by: _StrOrExpr | Sequence[_StrOrExpr], + right_on: _StrOrExpr, + right_by: _StrOrExpr | Sequence[_StrOrExpr], + tolerance: int, + ) -> None: ... diff --git a/python/pyarrow-stubs/_compute.pyi b/python/pyarrow-stubs/_compute.pyi index 3108cb063747..8afc49c48749 100644 --- a/python/pyarrow-stubs/_compute.pyi +++ b/python/pyarrow-stubs/_compute.pyi @@ -15,11 +15,532 @@ # specific language governing permissions and limitations # under the License. -# Placeholder stub - complete annotations in future PR. -# At runtime, these symbols are provided by the pyarrow.lib C extension. +from collections.abc import Callable, Hashable, Iterable, Mapping, Sequence +from types import EllipsisType +from typing import Any, ClassVar, Literal, TypeAlias, TypedDict -from typing import Any, TypeAlias +# Placeholders (Any) until ipc.pyi and scalar.pyi are annotated; mypy +# rejects them as types when imported through pyarrow.lib. +from pyarrow.__lib.ipc import RecordBatchReader +from pyarrow.__lib.scalar import Scalar +from pyarrow._stubs_typing import ( + NullEncoding, + NullPlacement, + NullSelectionBehavior, + Order, + TimeUnit, +) +from pyarrow.lib import ( + Array, + Buffer, + ChunkedArray, + DataType, + KeyValueMetadata, + MemoryPool, + Schema, + _Weakrefable, +) -Expression: TypeAlias = Any +_RoundMode: TypeAlias = Literal[ + "down", + "up", + "towards_zero", + "towards_infinity", + "half_down", + "half_up", + "half_towards_zero", + "half_towards_infinity", + "half_to_even", + "half_to_odd", +] +_DateTimeUnit: TypeAlias = Literal[ + "year", + "quarter", + "month", + "week", + "day", + "hour", + "minute", + "second", + "millisecond", + "microsecond", + "nanosecond", +] +# Sort keys are (name, order) or (name, order, null_placement) tuples; the +# null_placement arguments of the options are deprecated. +_SortKey: TypeAlias = ( + tuple[str | Expression, Order] | tuple[str | Expression, Order, NullPlacement] +) +_CountMode: TypeAlias = Literal["only_valid", "only_null", "all"] +_TimezoneResolution: TypeAlias = Literal["raise", "earliest", "latest"] -def __getattr__(name: str) -> Any: ... +class Kernel(_Weakrefable): ... + +class Function(_Weakrefable): + @property + def arity(self) -> int | EllipsisType: ... + @property + def kind( + self, + ) -> Literal["scalar", "vector", "scalar_aggregate", "hash_aggregate", "meta"]: ... + @property + def name(self) -> str: ... + @property + def num_kernels(self) -> int: ... + def call( + self, + args: Iterable[Any], + options: FunctionOptions | None = None, + memory_pool: MemoryPool | None = None, + length: int | None = None, + ) -> Any: ... + +class FunctionOptions(_Weakrefable): + __hash__: ClassVar[None] # type: ignore[assignment] + + def serialize(self) -> Buffer: ... + @staticmethod + def deserialize(buf: Buffer) -> FunctionOptions: ... + +class FunctionRegistry(_Weakrefable): + def get_function(self, name: str) -> Function: ... + def list_functions(self) -> list[str]: ... + +class HashAggregateFunction(Function): ... +class HashAggregateKernel(Kernel): ... +class ScalarAggregateFunction(Function): ... +class ScalarAggregateKernel(Kernel): ... +class ScalarFunction(Function): ... +class ScalarKernel(Kernel): ... +class VectorFunction(Function): ... +class VectorKernel(Kernel): ... + +# ==================== Option classes ==================== + +class ArraySortOptions(FunctionOptions): + def __init__( + self, + order: Order = "ascending", + *, + null_placement: NullPlacement = "at_end", + ) -> None: ... + +class AssumeTimezoneOptions(FunctionOptions): + def __init__( + self, + timezone: str, + *, + ambiguous: _TimezoneResolution = "raise", + nonexistent: _TimezoneResolution = "raise", + ) -> None: ... + +class CastOptions(FunctionOptions): + allow_int_overflow: bool + allow_time_truncate: bool + allow_time_overflow: bool + allow_decimal_truncate: bool + allow_float_truncate: bool + allow_invalid_utf8: bool + + def __init__( + self, + target_type: DataType | None = None, + *, + allow_int_overflow: bool | None = None, + allow_time_truncate: bool | None = None, + allow_time_overflow: bool | None = None, + allow_decimal_truncate: bool | None = None, + allow_float_truncate: bool | None = None, + allow_invalid_utf8: bool | None = None, + ) -> None: ... + @staticmethod + def safe(target_type: DataType | None = None) -> CastOptions: ... + @staticmethod + def unsafe(target_type: DataType | None = None) -> CastOptions: ... + def is_safe(self) -> bool: ... + +class CountOptions(FunctionOptions): + def __init__(self, mode: _CountMode = "only_valid") -> None: ... + +class CumulativeOptions(FunctionOptions): + def __init__( + self, start: Scalar | None = None, *, skip_nulls: bool = False + ) -> None: ... + +class DayOfWeekOptions(FunctionOptions): + def __init__( + self, *, count_from_zero: bool = True, week_start: int = 1 + ) -> None: ... + +class DictionaryEncodeOptions(FunctionOptions): + def __init__(self, null_encoding: NullEncoding = "mask") -> None: ... + +class RunEndEncodeOptions(FunctionOptions): + def __init__(self, run_end_type: DataType | str = ...) -> None: ... + +class ElementWiseAggregateOptions(FunctionOptions): + def __init__(self, *, skip_nulls: bool = True) -> None: ... + +class ExtractRegexOptions(FunctionOptions): + def __init__(self, pattern: str) -> None: ... + +class ExtractRegexSpanOptions(FunctionOptions): + def __init__(self, pattern: str) -> None: ... + +class FilterOptions(FunctionOptions): + def __init__( + self, null_selection_behavior: NullSelectionBehavior = "drop" + ) -> None: ... + +class IndexOptions(FunctionOptions): + def __init__(self, value: Scalar) -> None: ... + +class InversePermutationOptions(FunctionOptions): + def __init__( + self, max_index: int = -1, output_type: DataType | None = None + ) -> None: ... + +class JoinOptions(FunctionOptions): + def __init__( + self, + null_handling: Literal["emit_null", "skip", "replace"] = "emit_null", + null_replacement: str = "", + ) -> None: ... + +class ListSliceOptions(FunctionOptions): + def __init__( + self, + start: int, + stop: int | None = None, + step: int = 1, + return_fixed_size_list: bool | None = None, + ) -> None: ... + +class ListFlattenOptions(FunctionOptions): + def __init__(self, recursive: bool = False) -> None: ... + +class MakeStructOptions(FunctionOptions): + def __init__( + self, + field_names: Sequence[str] = (), + *, + field_nullability: Sequence[bool] | None = None, + field_metadata: Sequence[KeyValueMetadata] | None = None, + ) -> None: ... + +class MapLookupOptions(FunctionOptions): + def __init__( + self, query_key: Any, occurrence: Literal["first", "last", "all"] + ) -> None: ... + +class MatchSubstringOptions(FunctionOptions): + def __init__(self, pattern: str, *, ignore_case: bool = False) -> None: ... + +class ModeOptions(FunctionOptions): + def __init__( + self, n: int = 1, *, skip_nulls: bool = True, min_count: int = 0 + ) -> None: ... + +class NullOptions(FunctionOptions): + def __init__(self, *, nan_is_null: bool = False) -> None: ... + +class PadOptions(FunctionOptions): + def __init__( + self, width: int, padding: str = " ", lean_left_on_odd_padding: bool = True + ) -> None: ... + +class PairwiseOptions(FunctionOptions): + def __init__(self, period: int = 1) -> None: ... + +class PartitionNthOptions(FunctionOptions): + def __init__( + self, pivot: int, *, null_placement: NullPlacement = "at_end" + ) -> None: ... + +class WinsorizeOptions(FunctionOptions): + def __init__(self, lower_limit: float, upper_limit: float) -> None: ... + +class QuantileOptions(FunctionOptions): + def __init__( + self, + q: float | Sequence[float] = 0.5, + *, + interpolation: Literal[ + "linear", "lower", "higher", "nearest", "midpoint" + ] = "linear", + skip_nulls: bool = True, + min_count: int = 0, + ) -> None: ... + +class RandomOptions(FunctionOptions): + def __init__(self, *, initializer: Hashable = "system") -> None: ... + +class RankOptions(FunctionOptions): + def __init__( + self, + sort_keys: Order | Sequence[_SortKey] = "ascending", + *, + null_placement: NullPlacement | None = None, + tiebreaker: Literal["min", "max", "first", "dense"] = "first", + ) -> None: ... + +class RankQuantileOptions(FunctionOptions): + def __init__( + self, + sort_keys: Order | Sequence[_SortKey] = "ascending", + *, + null_placement: NullPlacement | None = None, + ) -> None: ... + +class PivotWiderOptions(FunctionOptions): + def __init__( + self, + key_names: Sequence[str], + *, + unexpected_key_behavior: Literal["ignore", "raise"] = "ignore", + ) -> None: ... + +class ReplaceSliceOptions(FunctionOptions): + def __init__(self, start: int, stop: int, replacement: str) -> None: ... + +class ReplaceSubstringOptions(FunctionOptions): + def __init__( + self, pattern: str, replacement: str, *, max_replacements: int | None = None + ) -> None: ... + +class RoundBinaryOptions(FunctionOptions): + def __init__(self, round_mode: _RoundMode = "half_to_even") -> None: ... + +class RoundOptions(FunctionOptions): + def __init__( + self, ndigits: int = 0, round_mode: _RoundMode = "half_to_even" + ) -> None: ... + +class RoundTemporalOptions(FunctionOptions): + def __init__( + self, + multiple: int = 1, + unit: _DateTimeUnit = "day", + *, + week_starts_monday: bool = True, + ceil_is_strictly_greater: bool = False, + calendar_based_origin: bool = False, + ) -> None: ... + +class RoundToMultipleOptions(FunctionOptions): + def __init__( + self, + multiple: float | Scalar = 1.0, + round_mode: _RoundMode = "half_to_even", + ) -> None: ... + +class ScalarAggregateOptions(FunctionOptions): + def __init__(self, *, skip_nulls: bool = True, min_count: int = 1) -> None: ... + +class ScatterOptions(FunctionOptions): + def __init__(self, max_index: int = -1) -> None: ... + +class SearchSortedOptions(FunctionOptions): + def __init__(self, side: Literal["left", "right"] = "left") -> None: ... + +class SelectKOptions(FunctionOptions): + def __init__(self, k: int, sort_keys: Sequence[_SortKey]) -> None: ... + +class SetLookupOptions(FunctionOptions): + def __init__( + self, value_set: Array | ChunkedArray | Scalar, *, skip_nulls: bool = False + ) -> None: ... + +class SliceOptions(FunctionOptions): + def __init__(self, start: int, stop: int | None = None, step: int = 1) -> None: ... + +class SortOptions(FunctionOptions): + def __init__( + self, + sort_keys: Sequence[_SortKey] = (), + *, + null_placement: NullPlacement | None = None, + ) -> None: ... + +class SplitOptions(FunctionOptions): + def __init__( + self, *, max_splits: int | None = None, reverse: bool = False + ) -> None: ... + +class SplitPatternOptions(FunctionOptions): + def __init__( + self, pattern: str, *, max_splits: int | None = None, reverse: bool = False + ) -> None: ... + +class StrftimeOptions(FunctionOptions): + def __init__( + self, format: str = "%Y-%m-%dT%H:%M:%S", locale: str = "C" + ) -> None: ... + +class StrptimeOptions(FunctionOptions): + def __init__( + self, format: str, unit: TimeUnit, error_is_null: bool = False + ) -> None: ... + +class StructFieldOptions(FunctionOptions): + def __init__( + self, + indices: Sequence[str | bytes | int] | Expression | bytes | str | int, + ) -> None: ... + +class TakeOptions(FunctionOptions): + def __init__(self, *, boundscheck: bool = True) -> None: ... + +class TDigestOptions(FunctionOptions): + def __init__( + self, + q: float | Sequence[float] = 0.5, + *, + delta: int = 100, + buffer_size: int = 500, + skip_nulls: bool = True, + min_count: int = 0, + ) -> None: ... + +class TrimOptions(FunctionOptions): + def __init__(self, characters: str) -> None: ... + +class Utf8NormalizeOptions(FunctionOptions): + def __init__(self, form: Literal["NFC", "NFKC", "NFD", "NFKD"]) -> None: ... + +class VarianceOptions(FunctionOptions): + def __init__( + self, *, ddof: int = 0, skip_nulls: bool = True, min_count: int = 0 + ) -> None: ... + +class SkewOptions(FunctionOptions): + def __init__( + self, *, skip_nulls: bool = True, biased: bool = True, min_count: int = 0 + ) -> None: ... + +class WeekOptions(FunctionOptions): + def __init__( + self, + *, + week_starts_monday: bool = True, + count_from_zero: bool = False, + first_week_is_fully_in_year: bool = False, + ) -> None: ... + +class ZeroFillOptions(FunctionOptions): + def __init__(self, width: int, padding: str = "0") -> None: ... + +# ==================== Functions ==================== + +def call_function( + name: str, + args: list[Any], + options: FunctionOptions | None = None, + memory_pool: MemoryPool | None = None, + length: int | None = None, +) -> Any: ... +def function_registry() -> FunctionRegistry: ... +def get_function(name: str) -> Function: ... +def list_functions() -> list[str]: ... + +# ==================== User-defined functions ==================== + +def call_tabular_function( + function_name: str, + args: Iterable[Any] | None = None, + func_registry: FunctionRegistry | None = None, +) -> RecordBatchReader: ... + +class _FunctionDoc(TypedDict): + summary: str + description: str + +def register_scalar_function( + func: Callable[..., Any], + function_name: str, + function_doc: _FunctionDoc | dict[str, str], + in_types: Mapping[str, DataType], + out_type: DataType, + func_registry: FunctionRegistry | None = None, +) -> None: ... +def register_tabular_function( + func: Callable[..., Any], + function_name: str, + function_doc: _FunctionDoc | dict[str, str], + in_types: Mapping[str, DataType], + out_type: DataType, + func_registry: FunctionRegistry | None = None, +) -> None: ... +def register_aggregate_function( + func: Callable[..., Any], + function_name: str, + function_doc: _FunctionDoc | dict[str, str], + in_types: Mapping[str, DataType], + out_type: DataType, + func_registry: FunctionRegistry | None = None, +) -> None: ... +def register_vector_function( + func: Callable[..., Any], + function_name: str, + function_doc: _FunctionDoc | dict[str, str], + in_types: Mapping[str, DataType], + out_type: DataType, + func_registry: FunctionRegistry | None = None, +) -> None: ... + +class UdfContext: + @property + def batch_length(self) -> int: ... + @property + def memory_pool(self) -> MemoryPool: ... + +def _get_udf_context(memory_pool: MemoryPool, batch_length: int) -> UdfContext: ... + +# ==================== Expression ==================== + +class Expression(_Weakrefable): + __hash__: ClassVar[None] # type: ignore[assignment] + + @staticmethod + def from_substrait(message: bytes | Buffer) -> Expression: ... + def to_substrait( + self, schema: Schema, allow_arrow_extensions: bool = False + ) -> Buffer: ... + @staticmethod + def _call( + function_name: str, + arguments: list[Any], + options: FunctionOptions | None = None, + ) -> Expression: ... + @staticmethod + def _field(name_or_idx: str | int) -> Expression: ... + @staticmethod + def _nested_field(names: tuple[str | int, ...]) -> Expression: ... + @staticmethod + def _scalar(value: Any) -> Expression: ... + def __invert__(self) -> Expression: ... + # The Expression must be the left operand: the reflected methods, e.g. + # 1 + Expression, raise TypeError at runtime. + def __and__(self, other: object, /) -> Expression: ... + def __or__(self, other: object, /) -> Expression: ... + def __add__(self, other: object, /) -> Expression: ... + def __mul__(self, other: object, /) -> Expression: ... + def __sub__(self, other: object, /) -> Expression: ... + def __truediv__(self, other: object, /) -> Expression: ... + def __eq__(self, other: object, /) -> Expression: ... # type: ignore[override] + def __ne__(self, other: object, /) -> Expression: ... # type: ignore[override] + def __gt__(self, other: object, /) -> Expression: ... + def __lt__(self, other: object, /) -> Expression: ... + def __ge__(self, other: object, /) -> Expression: ... + def __le__(self, other: object, /) -> Expression: ... + def is_valid(self) -> Expression: ... + def is_null(self, nan_is_null: bool = False) -> Expression: ... + def is_nan(self) -> Expression: ... + def cast( + self, + type: DataType | str | None = None, + safe: bool | None = None, + options: CastOptions | None = None, + ) -> Expression: ... + def isin(self, values: Array | Iterable[Any]) -> Expression: ... + def equals(self, other: Expression) -> bool: ... diff --git a/python/pyarrow-stubs/_compute_docstrings.pyi b/python/pyarrow-stubs/_compute_docstrings.pyi new file mode 100644 index 000000000000..514a4e4269c6 --- /dev/null +++ b/python/pyarrow-stubs/_compute_docstrings.pyi @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +function_doc_additions: dict[str, str] diff --git a/python/pyarrow-stubs/_stubs_typing.pyi b/python/pyarrow-stubs/_stubs_typing.pyi index 17ee2cffc316..0f9bcf887c55 100644 --- a/python/pyarrow-stubs/_stubs_typing.pyi +++ b/python/pyarrow-stubs/_stubs_typing.pyi @@ -24,6 +24,7 @@ from pyarrow.lib import Array, ChunkedArray from pyarrow import lib +ScalarLike: TypeAlias = Any Order: TypeAlias = Literal["ascending", "descending"] MapsAsPydicts: TypeAlias = Literal["lossy", "strict"] NullEncoding: TypeAlias = Literal["mask", "encode"] diff --git a/python/pyarrow-stubs/compute.pyi b/python/pyarrow-stubs/compute.pyi new file mode 100644 index 000000000000..827f123276cd --- /dev/null +++ b/python/pyarrow-stubs/compute.pyi @@ -0,0 +1,1672 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from collections.abc import Callable, Hashable, Iterable, Sequence +from typing import Any, Literal, ParamSpec, TypeAlias, TypeVar + +# Placeholders (Any) until scalar.pyi is annotated; mypy rejects them as +# types when imported through pyarrow.lib. +from pyarrow.__lib.scalar import ( + BinaryScalar, + BinaryViewScalar, + BooleanScalar, + Date32Scalar, + Date64Scalar, + Decimal32Scalar, + Decimal64Scalar, + Decimal128Scalar, + Decimal256Scalar, + DoubleScalar, + DurationScalar, + FixedSizeBinaryScalar, + FixedSizeListScalar, + FloatScalar, + HalfFloatScalar, + Int8Scalar, + Int16Scalar, + Int32Scalar, + Int64Scalar, + LargeBinaryScalar, + LargeListScalar, + LargeListViewScalar, + LargeStringScalar, + ListScalar, + ListViewScalar, + MonthDayNanoIntervalScalar, + NullScalar, + Scalar, + StringScalar, + StringViewScalar, + StructScalar, + Time32Scalar, + Time64Scalar, + TimestampScalar, + UInt8Scalar, + UInt16Scalar, + UInt32Scalar, + UInt64Scalar, +) +from pyarrow._compute import ( + ArraySortOptions as ArraySortOptions, + AssumeTimezoneOptions as AssumeTimezoneOptions, + CastOptions as CastOptions, + CountOptions as CountOptions, + CumulativeOptions as CumulativeOptions, + DayOfWeekOptions as DayOfWeekOptions, + DictionaryEncodeOptions as DictionaryEncodeOptions, + ElementWiseAggregateOptions as ElementWiseAggregateOptions, + Expression as Expression, + ExtractRegexOptions as ExtractRegexOptions, + ExtractRegexSpanOptions as ExtractRegexSpanOptions, + FilterOptions as FilterOptions, + Function as Function, + FunctionOptions as FunctionOptions, + FunctionRegistry as FunctionRegistry, + HashAggregateFunction as HashAggregateFunction, + HashAggregateKernel as HashAggregateKernel, + IndexOptions as IndexOptions, + InversePermutationOptions as InversePermutationOptions, + JoinOptions as JoinOptions, + Kernel as Kernel, + ListFlattenOptions as ListFlattenOptions, + ListSliceOptions as ListSliceOptions, + MakeStructOptions as MakeStructOptions, + MapLookupOptions as MapLookupOptions, + MatchSubstringOptions as MatchSubstringOptions, + ModeOptions as ModeOptions, + NullOptions as NullOptions, + PadOptions as PadOptions, + PairwiseOptions as PairwiseOptions, + PartitionNthOptions as PartitionNthOptions, + PivotWiderOptions as PivotWiderOptions, + QuantileOptions as QuantileOptions, + RandomOptions as RandomOptions, + RankOptions as RankOptions, + RankQuantileOptions as RankQuantileOptions, + ReplaceSliceOptions as ReplaceSliceOptions, + ReplaceSubstringOptions as ReplaceSubstringOptions, + RoundBinaryOptions as RoundBinaryOptions, + RoundOptions as RoundOptions, + RoundTemporalOptions as RoundTemporalOptions, + RoundToMultipleOptions as RoundToMultipleOptions, + RunEndEncodeOptions as RunEndEncodeOptions, + ScalarAggregateFunction as ScalarAggregateFunction, + ScalarAggregateKernel as ScalarAggregateKernel, + ScalarAggregateOptions as ScalarAggregateOptions, + ScalarFunction as ScalarFunction, + ScalarKernel as ScalarKernel, + ScatterOptions as ScatterOptions, + SearchSortedOptions as SearchSortedOptions, + SelectKOptions as SelectKOptions, + SetLookupOptions as SetLookupOptions, + SkewOptions as SkewOptions, + SliceOptions as SliceOptions, + SortOptions as SortOptions, + SplitOptions as SplitOptions, + SplitPatternOptions as SplitPatternOptions, + StrftimeOptions as StrftimeOptions, + StrptimeOptions as StrptimeOptions, + StructFieldOptions as StructFieldOptions, + TakeOptions as TakeOptions, + TDigestOptions as TDigestOptions, + TrimOptions as TrimOptions, + UdfContext as UdfContext, + Utf8NormalizeOptions as Utf8NormalizeOptions, + VarianceOptions as VarianceOptions, + VectorFunction as VectorFunction, + VectorKernel as VectorKernel, + WeekOptions as WeekOptions, + WinsorizeOptions as WinsorizeOptions, + ZeroFillOptions as ZeroFillOptions, + call_function as call_function, + call_tabular_function as call_tabular_function, + function_registry as function_registry, + get_function as get_function, + list_functions as list_functions, + register_aggregate_function as register_aggregate_function, + register_scalar_function as register_scalar_function, + register_tabular_function as register_tabular_function, + register_vector_function as register_vector_function, +) +from pyarrow._compute import _CountMode, _DateTimeUnit, _RoundMode, _SortKey +from pyarrow._stubs_typing import ( + ArrayLike, + Indices, + Mask, + NullPlacement, + Order, + ScalarLike, + TimeUnit, +) +from pyarrow.lib import ( + Array, + BaseListArray, + BinaryArray, + BinaryViewArray, + BooleanArray, + ChunkedArray, + DataType, + Date32Array, + Date64Array, + Decimal32Array, + Decimal64Array, + Decimal128Array, + Decimal256Array, + DoubleArray, + DurationArray, + FixedSizeBinaryArray, + FloatingPointArray, + Int32Array, + Int64Array, + IntegerArray, + KeyValueMetadata, + LargeBinaryArray, + LargeStringArray, + MemoryPool, + MonthDayNanoIntervalArray, + NumericArray, + RecordBatch, + RunEndEncodedArray, + StringArray, + StringViewArray, + StructArray, + Table, + Time32Array, + Time64Array, + TimestampArray, + UInt64Array, +) + +_P = ParamSpec("_P") +_R = TypeVar("_R") + +# Stub-only helper: the compute functions that share a signature are +# annotated once and the others are declared as copies of it. +def _clone_signature(f: Callable[_P, _R]) -> Callable[_P, _R]: ... +def field(*name_or_index: str | bytes | tuple[str | int, ...] | int) -> Expression: ... +def scalar(value: Any) -> Expression: ... + +# The inputs and outputs of the compute functions, by kind of data. The +# scalar classes are placeholders (Any) until scalar.pyi is annotated. +_SignedIntegerScalar: TypeAlias = Int8Scalar | Int16Scalar | Int32Scalar | Int64Scalar +_UnsignedIntegerScalar: TypeAlias = ( + UInt8Scalar | UInt16Scalar | UInt32Scalar | UInt64Scalar +) +_IntegerScalar: TypeAlias = _SignedIntegerScalar | _UnsignedIntegerScalar +_FloatScalar: TypeAlias = HalfFloatScalar | FloatScalar | DoubleScalar +_DecimalScalar: TypeAlias = ( + Decimal32Scalar | Decimal64Scalar | Decimal128Scalar | Decimal256Scalar +) +_NonFloatNumericScalar: TypeAlias = _IntegerScalar | _DecimalScalar +_NumericScalar: TypeAlias = _IntegerScalar | _FloatScalar | _DecimalScalar +_BinaryScalar: TypeAlias = ( + BinaryScalar | LargeBinaryScalar | BinaryViewScalar | FixedSizeBinaryScalar +) +_StringScalar: TypeAlias = StringScalar | LargeStringScalar | StringViewScalar +_StringOrBinaryScalar: TypeAlias = _StringScalar | _BinaryScalar +_ListScalar: TypeAlias = ( + ListScalar + | LargeListScalar + | ListViewScalar + | LargeListViewScalar + | FixedSizeListScalar +) +_TemporalScalar: TypeAlias = ( + Date32Scalar + | Date64Scalar + | Time32Scalar + | Time64Scalar + | TimestampScalar + | DurationScalar + | MonthDayNanoIntervalScalar +) +_NumericOrDurationScalar: TypeAlias = _NumericScalar | DurationScalar +_NumericOrTemporalScalar: TypeAlias = _NumericScalar | _TemporalScalar + +# pyarrow.array() and most of the API return plain Array and ChunkedArray +# instances, as these classes aren't generic. So the compute functions accept +# any Array or ChunkedArray, and only the return types say which kind of array +# the result is, e.g. a StringArray for a string input. The ChunkedArray of a +# chunked input is the same for every kind. +_ArrayOrChunkedArray: TypeAlias = Array | ChunkedArray +_ScalarOrArray: TypeAlias = Scalar | Array | ChunkedArray +_DecimalArray: TypeAlias = ( + Decimal32Array | Decimal64Array | Decimal128Array | Decimal256Array +) +# NumericArray includes the date, time, timestamp and duration arrays. +_NumericArray: TypeAlias = NumericArray | _DecimalArray | ChunkedArray +_NumericOrDurationArray: TypeAlias = _NumericArray +_NumericOrTemporalArray: TypeAlias = _NumericArray | MonthDayNanoIntervalArray +_IntegerArray: TypeAlias = IntegerArray | ChunkedArray +_FloatArray: TypeAlias = FloatingPointArray | ChunkedArray +_BooleanArray: TypeAlias = BooleanArray | ChunkedArray +_StringArray: TypeAlias = ( + StringArray | LargeStringArray | StringViewArray | ChunkedArray +) +_BinaryArray: TypeAlias = ( + BinaryArray + | LargeBinaryArray + | BinaryViewArray + | FixedSizeBinaryArray + | ChunkedArray +) +_StringOrBinaryArray: TypeAlias = _StringArray | _BinaryArray +_TemporalArray: TypeAlias = ( + Date32Array + | Date64Array + | Time32Array + | Time64Array + | TimestampArray + | DurationArray + | MonthDayNanoIntervalArray + | ChunkedArray +) +_ListArray: TypeAlias = BaseListArray | ChunkedArray + +# =============================== 1. Aggregation =============================== + +def array_take( + array: _ArrayOrChunkedArray | RecordBatch | Table | Expression, + indices: Indices | Expression, + /, + *, + boundscheck: bool = True, + options: TakeOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _ArrayOrChunkedArray | RecordBatch | Table | Expression: ... + +# ========================= 1.1 functions ========================= + +def all( + array: BooleanScalar | _ArrayOrChunkedArray | Expression, + /, + *, + skip_nulls: bool = True, + min_count: int = 1, + options: ScalarAggregateOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> BooleanScalar | Expression: ... + +any = _clone_signature(all) + +def approximate_median( + array: _NumericScalar | _ArrayOrChunkedArray | Expression, + /, + *, + skip_nulls: bool = True, + min_count: int = 1, + options: ScalarAggregateOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> DoubleScalar | Expression: ... +def count( + array: _ArrayOrChunkedArray | Expression, + /, + mode: _CountMode = "only_valid", + *, + options: CountOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> Int64Scalar | Expression: ... +def count_distinct( + array: _ArrayOrChunkedArray | Expression, + /, + mode: _CountMode = "only_valid", + *, + options: CountOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> Int64Scalar | Expression: ... +def first( + array: _ArrayOrChunkedArray | Expression, + /, + *, + skip_nulls: bool = True, + min_count: int = 1, + options: ScalarAggregateOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> Scalar | Expression: ... + +last = _clone_signature(first) + +def first_last( + array: _ArrayOrChunkedArray | Iterable[Any] | Expression, + /, + *, + skip_nulls: bool = True, + min_count: int = 1, + options: ScalarAggregateOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> StructScalar | Expression: ... +def index( + data: _ArrayOrChunkedArray, + value: ScalarLike, + start: int | None = None, + end: int | None = None, + *, + memory_pool: MemoryPool | None = None, +) -> Int64Scalar: ... + +max = _clone_signature(first) +min = _clone_signature(first) +min_max = _clone_signature(first_last) + +def mean( + array: _NumericScalar | _ArrayOrChunkedArray | Expression, + /, + *, + skip_nulls: bool = True, + min_count: int = 1, + options: ScalarAggregateOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> Scalar | Expression: ... +def mode( + array: _NumericScalar | _ArrayOrChunkedArray | Expression, + /, + n: int = 1, + *, + skip_nulls: bool = True, + min_count: int = 0, + options: ModeOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> StructArray | Expression: ... +def product( + array: _NumericScalar | _ArrayOrChunkedArray | Expression, + /, + *, + skip_nulls: bool = True, + min_count: int = 1, + options: ScalarAggregateOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _NumericScalar | Expression: ... +def quantile( + array: _NumericScalar | _ArrayOrChunkedArray | Expression, + /, + q: float | Sequence[float] = 0.5, + *, + interpolation: Literal[ + "linear", "lower", "higher", "nearest", "midpoint" + ] = "linear", + skip_nulls: bool = True, + min_count: int = 0, + options: QuantileOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> DoubleArray | Expression: ... +def stddev( + array: _NumericScalar | _ArrayOrChunkedArray | Expression, + /, + *, + ddof: float = 0, + skip_nulls: bool = True, + min_count: int = 0, + options: VarianceOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> DoubleScalar | Expression: ... +def sum( + array: _NumericScalar | _ArrayOrChunkedArray | Expression, + /, + *, + skip_nulls: bool = True, + min_count: int = 1, + options: ScalarAggregateOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _NumericScalar | Expression: ... +def tdigest( + array: _NumericScalar | _ArrayOrChunkedArray | Expression, + /, + q: float | Sequence[float] = 0.5, + *, + delta: int = 100, + buffer_size: int = 500, + skip_nulls: bool = True, + min_count: int = 0, + options: TDigestOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> DoubleArray | Expression: ... +def variance( + array: _NumericScalar | _ArrayOrChunkedArray | ArrayLike | Expression, + /, + *, + ddof: int = 0, + skip_nulls: bool = True, + min_count: int = 0, + options: VarianceOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> DoubleScalar | Expression: ... +def winsorize( + array: _ArrayOrChunkedArray | Expression, + /, + lower_limit: float, + upper_limit: float, + *, + options: WinsorizeOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _NumericArray | Expression: ... +def skew( + array: _NumericScalar | _ArrayOrChunkedArray | ArrayLike | Expression, + /, + *, + skip_nulls: bool = True, + biased: bool = True, + min_count: int = 0, + options: SkewOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> DoubleScalar | Expression: ... +def kurtosis( + array: _NumericScalar | _ArrayOrChunkedArray | ArrayLike | Expression, + /, + *, + skip_nulls: bool = True, + biased: bool = True, + min_count: int = 0, + options: SkewOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> DoubleScalar | Expression: ... +def top_k_unstable( + values: _ArrayOrChunkedArray | RecordBatch | Table, + k: int, + sort_keys: Sequence[str] | None = None, + null_placements: Sequence[NullPlacement] | None = None, + *, + memory_pool: MemoryPool | None = None, +) -> UInt64Array: ... +def bottom_k_unstable( + values: _ArrayOrChunkedArray | RecordBatch | Table, + k: int, + sort_keys: Sequence[str] | None = None, + null_placements: Sequence[NullPlacement] | None = None, + *, + memory_pool: MemoryPool | None = None, +) -> UInt64Array: ... + +# ========================= 2. Element-wise (“scalar”) functions ========= + +# ========================= 2.1 Arithmetic ========================= +def abs( + x: _NumericOrDurationScalar | _ArrayOrChunkedArray | Expression | float, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _NumericOrDurationScalar | _NumericOrDurationArray | Expression: ... + +abs_checked = _clone_signature(abs) + +def add( + x: _NumericOrTemporalScalar | _ArrayOrChunkedArray | ArrayLike | int | Expression, + y: (_NumericOrTemporalScalar | _ArrayOrChunkedArray | ArrayLike | int | Expression), + /, + *, + memory_pool: MemoryPool | None = None, +) -> _NumericOrTemporalScalar | _NumericOrTemporalArray | Expression: ... + +add_checked = _clone_signature(add) + +def divide( + x: _NumericOrTemporalScalar | _ArrayOrChunkedArray | Expression | float, + y: _NumericOrTemporalScalar | _ArrayOrChunkedArray | Expression | float, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _NumericOrTemporalScalar | _NumericOrTemporalArray | Expression: ... + +divide_checked = _clone_signature(divide) + +def hypot( + x: _NumericScalar | _ArrayOrChunkedArray | float | Expression, + y: _NumericScalar | _ArrayOrChunkedArray | float | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _FloatScalar | _FloatArray | Expression: ... +def modulo( + dividend: _NumericScalar | _ArrayOrChunkedArray | float | Expression, + divisor: _NumericScalar | _ArrayOrChunkedArray | float | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _NumericScalar | _NumericArray | Expression: ... + +modulo_checked = _clone_signature(modulo) +remainder = _clone_signature(modulo) +remainder_checked = _clone_signature(modulo) + +def exp( + exponent: _ArrayOrChunkedArray + | _FloatScalar + | _NonFloatNumericScalar + | DoubleScalar + | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _FloatArray | DoubleArray | _FloatScalar | DoubleScalar | Expression: ... + +expm1 = _clone_signature(exp) +multiply = _clone_signature(add) +multiply_checked = _clone_signature(add) + +def negate( + x: _NumericOrDurationScalar | _ArrayOrChunkedArray | Expression | float, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _NumericOrDurationScalar | _NumericOrDurationArray | Expression: ... + +negate_checked = _clone_signature(negate) + +def power( + base: _NumericScalar | Expression | _ArrayOrChunkedArray | float, + exponent: _NumericScalar | Expression | _ArrayOrChunkedArray | float, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _NumericScalar | _NumericArray | Expression: ... + +power_checked = _clone_signature(power) + +def sign( + x: _ArrayOrChunkedArray | _NumericOrDurationScalar | Expression | float, + /, + *, + memory_pool: MemoryPool | None = None, +) -> Int8Scalar | _FloatScalar | NumericArray | ChunkedArray | Expression: ... +def sqrt( + x: _ArrayOrChunkedArray | _NumericScalar | Expression | float, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _FloatArray | _FloatScalar | Expression: ... + +sqrt_checked = _clone_signature(sqrt) + +subtract = _clone_signature(add) +subtract_checked = _clone_signature(add) + +# ========================= 2.1 Bit-wise functions ========================= + +def bit_wise_and( + x: _NumericScalar | _ArrayOrChunkedArray | Expression | float, + y: _NumericScalar | _ArrayOrChunkedArray | Expression | float, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _NumericScalar | _NumericArray | Expression: ... +def bit_wise_not( + x: _NumericScalar | _ArrayOrChunkedArray | Expression | float, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _NumericScalar | _NumericArray | Expression: ... + +bit_wise_or = _clone_signature(bit_wise_and) +bit_wise_xor = _clone_signature(bit_wise_and) +shift_left = _clone_signature(bit_wise_and) +shift_left_checked = _clone_signature(bit_wise_and) +shift_right = _clone_signature(bit_wise_and) +shift_right_checked = _clone_signature(bit_wise_and) + +# ========================= 2.2 Rounding functions ========================= + +def ceil( + x: _FloatScalar | _ArrayOrChunkedArray | Expression | float, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _FloatScalar | _FloatArray | Expression: ... + +floor = _clone_signature(ceil) + +def round( + x: _NumericScalar | _ArrayOrChunkedArray | Iterable[Any] | Expression | float, + /, + ndigits: int = 0, + round_mode: _RoundMode = "half_to_even", + *, + options: RoundOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _NumericScalar | _NumericArray | Expression: ... +def round_to_multiple( + x: _NumericScalar | _ArrayOrChunkedArray | Iterable[Any] | Expression | float, + /, + multiple: float | _NumericScalar = 1.0, + round_mode: _RoundMode = "half_to_even", + *, + options: RoundToMultipleOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _NumericScalar | _NumericArray | Expression: ... +def round_binary( + x: _NumericScalar | _ArrayOrChunkedArray | Iterable[Any] | float | Expression, + s: _SignedIntegerScalar | _ArrayOrChunkedArray | int | Expression, + /, + round_mode: _RoundMode = "half_to_even", + *, + options: RoundBinaryOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _NumericScalar | _NumericArray | Expression: ... + +trunc = _clone_signature(ceil) + +# ========================= 2.3 Logarithmic functions ========================= + +def ln( + x: _NumericScalar | _ArrayOrChunkedArray | Expression | float, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _FloatScalar | _FloatArray | Expression: ... + +ln_checked = _clone_signature(ln) +log10 = _clone_signature(ln) +log10_checked = _clone_signature(ln) +log1p = _clone_signature(ln) +log1p_checked = _clone_signature(ln) +log2 = _clone_signature(ln) +log2_checked = _clone_signature(ln) + +def logb( + x: _NumericScalar | _ArrayOrChunkedArray | float | Expression, + b: _NumericScalar | _ArrayOrChunkedArray | float | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _FloatScalar | _FloatArray | Expression: ... + +logb_checked = _clone_signature(logb) + +# ========================= 2.4 Trigonometric functions ========================= +acos = _clone_signature(ln) +acos_checked = _clone_signature(ln) +acosh = _clone_signature(ln) +acosh_checked = _clone_signature(ln) +asin = _clone_signature(ln) +asin_checked = _clone_signature(ln) +asinh = _clone_signature(ln) +atan = _clone_signature(ln) +atanh_checked = _clone_signature(ln) +atanh = _clone_signature(ln) +cos = _clone_signature(ln) +cos_checked = _clone_signature(ln) +cosh = _clone_signature(ln) +sin = _clone_signature(ln) +sin_checked = _clone_signature(ln) +sinh = _clone_signature(ln) +tan = _clone_signature(ln) +tan_checked = _clone_signature(ln) +tanh = _clone_signature(ln) + +def atan2( + y: _NumericScalar | _ArrayOrChunkedArray | float | Expression, + x: _NumericScalar | _ArrayOrChunkedArray | float | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _FloatScalar | _FloatArray | Expression: ... + +# ========================= 2.5 Comparisons functions ========================= +def equal( + x: _ScalarOrArray | ScalarLike | Expression, + y: _ScalarOrArray | ScalarLike | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> BooleanScalar | _BooleanArray | Expression: ... + +greater = _clone_signature(equal) +greater_equal = _clone_signature(equal) +less = _clone_signature(equal) +less_equal = _clone_signature(equal) +not_equal = _clone_signature(equal) + +def max_element_wise( + *args: _ScalarOrArray | Expression | ScalarLike | ArrayLike, + skip_nulls: bool = True, + options: ElementWiseAggregateOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _ScalarOrArray | Expression: ... + +min_element_wise = _clone_signature(max_element_wise) + +# ========================= 2.6 Logical functions ========================= + +def and_( + x: BooleanScalar | _ArrayOrChunkedArray | bool | Expression, + y: BooleanScalar | _ArrayOrChunkedArray | bool | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> BooleanScalar | _BooleanArray | Expression: ... + +and_kleene = _clone_signature(and_) +and_not = _clone_signature(and_) +and_not_kleene = _clone_signature(and_) +or_ = _clone_signature(and_) +or_kleene = _clone_signature(and_) +xor = _clone_signature(and_) + +def invert( + x: BooleanScalar | _ArrayOrChunkedArray | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> BooleanScalar | _BooleanArray | Expression: ... + +# ========================= 2.10 String predicates ========================= +def ascii_is_alnum( + strings: _StringScalar | _ArrayOrChunkedArray | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> BooleanScalar | _BooleanArray | Expression: ... + +ascii_is_alpha = _clone_signature(ascii_is_alnum) +ascii_is_decimal = _clone_signature(ascii_is_alnum) +ascii_is_lower = _clone_signature(ascii_is_alnum) +ascii_is_printable = _clone_signature(ascii_is_alnum) +ascii_is_space = _clone_signature(ascii_is_alnum) +ascii_is_upper = _clone_signature(ascii_is_alnum) +utf8_is_alnum = _clone_signature(ascii_is_alnum) +utf8_is_alpha = _clone_signature(ascii_is_alnum) +utf8_is_decimal = _clone_signature(ascii_is_alnum) +utf8_is_digit = _clone_signature(ascii_is_alnum) +utf8_is_lower = _clone_signature(ascii_is_alnum) +utf8_is_numeric = _clone_signature(ascii_is_alnum) +utf8_is_printable = _clone_signature(ascii_is_alnum) +utf8_is_space = _clone_signature(ascii_is_alnum) +utf8_is_upper = _clone_signature(ascii_is_alnum) +ascii_is_title = _clone_signature(ascii_is_alnum) +utf8_is_title = _clone_signature(ascii_is_alnum) +string_is_ascii = _clone_signature(ascii_is_alnum) + +# ========================= 2.11 String transforms ========================= + +def ascii_capitalize( + strings: _StringScalar | _ArrayOrChunkedArray | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _StringScalar | _StringArray | Expression: ... + +ascii_lower = _clone_signature(ascii_capitalize) +ascii_reverse = _clone_signature(ascii_capitalize) +ascii_swapcase = _clone_signature(ascii_capitalize) +ascii_title = _clone_signature(ascii_capitalize) +ascii_upper = _clone_signature(ascii_capitalize) + +def binary_length( + strings: _StringOrBinaryScalar | _ArrayOrChunkedArray | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> ( + Int32Scalar | Int64Scalar | Int32Array | Int64Array | ChunkedArray | Expression +): ... +def binary_repeat( + strings: _StringOrBinaryScalar | _ArrayOrChunkedArray | Expression, + num_repeats: int | _ArrayOrChunkedArray | Iterable[int | None] | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _StringOrBinaryScalar | _StringOrBinaryArray | Expression: ... +def binary_replace_slice( + strings: _StringOrBinaryScalar | _ArrayOrChunkedArray | Expression, + /, + start: int, + stop: int, + replacement: str | bytes, + *, + options: ReplaceSliceOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _StringOrBinaryScalar | _StringOrBinaryArray | Expression: ... +def binary_reverse( + strings: _BinaryScalar | _ArrayOrChunkedArray | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _BinaryScalar | _BinaryArray | Expression: ... +def replace_substring( + strings: _StringScalar | _ArrayOrChunkedArray | Expression, + /, + pattern: str | bytes, + replacement: str | bytes, + *, + max_replacements: int | None = None, + options: ReplaceSubstringOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _StringScalar | _StringArray | Expression: ... + +replace_substring_regex = _clone_signature(replace_substring) + +def utf8_capitalize( + strings: _StringScalar | _ArrayOrChunkedArray | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _StringScalar | _StringArray | Expression: ... +def utf8_length( + strings: _StringScalar | _ArrayOrChunkedArray | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> ( + Int32Scalar | Int64Scalar | Int32Array | Int64Array | ChunkedArray | Expression +): ... + +utf8_lower = _clone_signature(utf8_capitalize) + +def utf8_replace_slice( + strings: _StringScalar | _ArrayOrChunkedArray | Expression, + /, + start: int, + stop: int, + replacement: str | bytes, + *, + options: ReplaceSliceOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _StringScalar | _StringArray | Expression: ... + +utf8_reverse = _clone_signature(utf8_capitalize) +utf8_swapcase = _clone_signature(utf8_capitalize) +utf8_title = _clone_signature(utf8_capitalize) +utf8_upper = _clone_signature(utf8_capitalize) + +# ========================= 2.12 String padding ========================= + +def ascii_center( + strings: _StringScalar | _ArrayOrChunkedArray | Expression, + /, + width: int, + padding: str = " ", + lean_left_on_odd_padding: bool = True, + *, + options: PadOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _StringScalar | _StringArray | Expression: ... + +ascii_lpad = _clone_signature(ascii_center) +ascii_rpad = _clone_signature(ascii_center) +utf8_center = _clone_signature(ascii_center) +utf8_lpad = _clone_signature(ascii_center) +utf8_rpad = _clone_signature(ascii_center) + +def utf8_zero_fill( + strings: _StringScalar | _ArrayOrChunkedArray | Expression, + /, + width: int, + padding: str = "0", + *, + options: ZeroFillOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _StringScalar | _StringArray | Expression: ... + +utf8_zfill = utf8_zero_fill + +# ========================= 2.13 String trimming ========================= + +def ascii_ltrim( + strings: _StringScalar | _ArrayOrChunkedArray | Expression, + /, + characters: str, + *, + options: TrimOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _StringScalar | _StringArray | Expression: ... + +ascii_rtrim = _clone_signature(ascii_ltrim) +ascii_trim = _clone_signature(ascii_ltrim) +utf8_ltrim = _clone_signature(ascii_ltrim) +utf8_rtrim = _clone_signature(ascii_ltrim) +utf8_trim = _clone_signature(ascii_ltrim) + +def ascii_ltrim_whitespace( + strings: _StringScalar | _ArrayOrChunkedArray | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _StringScalar | _StringArray | Expression: ... + +ascii_rtrim_whitespace = _clone_signature(ascii_ltrim_whitespace) +ascii_trim_whitespace = _clone_signature(ascii_ltrim_whitespace) +utf8_ltrim_whitespace = _clone_signature(ascii_ltrim_whitespace) +utf8_rtrim_whitespace = _clone_signature(ascii_ltrim_whitespace) +utf8_trim_whitespace = _clone_signature(ascii_ltrim_whitespace) + +# ========================= 2.14 String splitting ========================= + +def ascii_split_whitespace( + strings: _StringScalar | _ArrayOrChunkedArray | Expression, + /, + *, + max_splits: int | None = None, + reverse: bool = False, + options: SplitOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _ListScalar | _ListArray | Expression: ... +def split_pattern( + strings: _StringOrBinaryScalar | _ArrayOrChunkedArray | Expression, + /, + pattern: str, + *, + max_splits: int | None = None, + reverse: bool = False, + options: SplitOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _ListScalar | _ListArray | Expression: ... + +split_pattern_regex = _clone_signature(split_pattern) +utf8_split_whitespace = _clone_signature(ascii_split_whitespace) + +# ========================= 2.15 String component extraction ========================= + +def extract_regex( + strings: _StringOrBinaryScalar | _ArrayOrChunkedArray | Expression, + /, + pattern: str, + *, + options: ExtractRegexOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> StructScalar | StructArray | ChunkedArray | Expression: ... + +extract_regex_span = _clone_signature(extract_regex) + +# ========================= 2.16 String join ========================= +def binary_join( + strings: _ListScalar | _ArrayOrChunkedArray | Expression, + separator: str | bytes | _StringOrBinaryScalar | _ArrayOrChunkedArray | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _StringOrBinaryScalar | _StringOrBinaryArray | Expression: ... +def binary_join_element_wise( + *strings: str + | bytes + | _StringOrBinaryScalar + | _ArrayOrChunkedArray + | Iterable[Any] + | Expression, + null_handling: Literal["emit_null", "skip", "replace"] = "emit_null", + null_replacement: str = "", + options: JoinOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _StringOrBinaryScalar | _StringOrBinaryArray | Expression: ... + +# ========================= 2.17 String Slicing ========================= +def binary_slice( + strings: _BinaryScalar | _ArrayOrChunkedArray | Expression, + /, + start: int, + stop: int | None = None, + step: int = 1, + *, + options: SliceOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _BinaryScalar | _BinaryArray | Expression: ... +def utf8_slice_codeunits( + strings: _StringScalar | _ArrayOrChunkedArray | Expression, + /, + start: int, + stop: int | None = None, + step: int = 1, + *, + options: SliceOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _StringScalar | _StringArray | Expression: ... +def utf8_normalize( + strings: _StringScalar | _ArrayOrChunkedArray | Expression, + /, + form: Literal["NFC", "NFKC", "NFD", "NFKD"], + *, + options: Utf8NormalizeOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _StringScalar | _StringArray | Expression: ... + +# ========================= 2.18 Containment tests ========================= +def count_substring( + strings: _StringOrBinaryScalar | _ArrayOrChunkedArray | Expression, + /, + pattern: str, + *, + ignore_case: bool = False, + options: MatchSubstringOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> ( + Int32Scalar | Int64Scalar | Int32Array | Int64Array | ChunkedArray | Expression +): ... + +count_substring_regex = _clone_signature(count_substring) + +def ends_with( + strings: _StringOrBinaryScalar | _ArrayOrChunkedArray | Expression, + /, + pattern: str, + *, + ignore_case: bool = False, + options: MatchSubstringOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> BooleanScalar | _BooleanArray | Expression: ... + +find_substring = _clone_signature(count_substring) +find_substring_regex = _clone_signature(count_substring) + +def index_in( + values: _ScalarOrArray | Expression, + /, + value_set: _ArrayOrChunkedArray | Expression, + *, + skip_nulls: bool = False, + options: SetLookupOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> Int32Scalar | Int32Array | ChunkedArray | Expression: ... +def index_in_meta_binary( + values: _ScalarOrArray | Expression, + value_set: _ArrayOrChunkedArray | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> Int32Scalar | Int32Array | ChunkedArray | Expression: ... +def is_in( + values: _ScalarOrArray | Expression, + /, + value_set: _ArrayOrChunkedArray | Expression, + *, + skip_nulls: bool = False, + options: SetLookupOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> BooleanScalar | _BooleanArray | Expression: ... + +is_in_meta_binary = _clone_signature(index_in_meta_binary) +match_like = _clone_signature(ends_with) +match_substring = _clone_signature(ends_with) +match_substring_regex = _clone_signature(ends_with) +starts_with = _clone_signature(ends_with) + +# ========================= 2.19 Categorizations ========================= + +def is_finite( + values: _NumericScalar | NullScalar | _ArrayOrChunkedArray | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> BooleanScalar | _BooleanArray | Expression: ... + +is_inf = _clone_signature(is_finite) +is_nan = _clone_signature(is_finite) + +def is_null( + values: _ScalarOrArray | Expression, + /, + *, + nan_is_null: bool = False, + options: NullOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> BooleanScalar | _BooleanArray | Expression: ... +def is_valid( + values: _ScalarOrArray | Expression | ArrayLike, + /, + *, + memory_pool: MemoryPool | None = None, +) -> BooleanScalar | _BooleanArray | Expression: ... + +true_unless_null = _clone_signature(is_valid) + +# ========================= 2.20 Selecting / multiplexing ========================= + +def case_when( + cond: StructScalar | _ArrayOrChunkedArray | Expression, + /, + *cases: _ScalarOrArray | ArrayLike, + memory_pool: MemoryPool | None = None, +) -> _ScalarOrArray | Array | Expression: ... +def choose( + indices: ArrayLike | ScalarLike, + /, + *values: ArrayLike | ScalarLike, + memory_pool: MemoryPool | None = None, +) -> ArrayLike | ScalarLike: ... +def coalesce( + *values: _ScalarOrArray | Expression, memory_pool: MemoryPool | None = None +) -> _ScalarOrArray | Expression: ... +def fill_null( + values: _ScalarOrArray | ScalarLike, fill_value: ArrayLike | ScalarLike +) -> _ScalarOrArray | ScalarLike: ... +def if_else( + cond: ArrayLike | ScalarLike, + left: ArrayLike | ScalarLike, + right: ArrayLike | ScalarLike, + /, + *, + memory_pool: MemoryPool | None = None, +) -> ArrayLike | ScalarLike: ... + +# ========================= 2.21 Structural transforms ========================= + +def list_value_length( + lists: _ArrayOrChunkedArray | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> ( + Int32Scalar | Int64Scalar | Int32Array | Int64Array | ChunkedArray | Expression +): ... +def make_struct( + *args: _ScalarOrArray | Expression | ArrayLike, + field_names: Sequence[str] = (), + field_nullability: bool | None = None, + field_metadata: Sequence[KeyValueMetadata] | None = None, + options: MakeStructOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> StructScalar | StructArray | ChunkedArray | Expression: ... + +# ========================= 2.22 Conversions ========================= +def ceil_temporal( + timestamps: _TemporalScalar | _ArrayOrChunkedArray | Expression, + /, + multiple: int = 1, + unit: _DateTimeUnit = "day", + *, + week_starts_monday: bool = True, + ceil_is_strictly_greater: bool = False, + calendar_based_origin: bool = False, + options: RoundTemporalOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _TemporalScalar | _TemporalArray | Expression: ... + +floor_temporal = _clone_signature(ceil_temporal) +round_temporal = _clone_signature(ceil_temporal) + +def cast( + arr: _ScalarOrArray | Table, + target_type: DataType | str | None = None, + safe: bool | None = None, + options: CastOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> Scalar | Array | ChunkedArray | Table: ... +def strftime( + timestamps: _TemporalScalar | _ArrayOrChunkedArray | Expression, + /, + format: str = "%Y-%m-%dT%H:%M:%S", + locale: str = "C", + *, + options: StrftimeOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> StringScalar | StringArray | ChunkedArray | Expression: ... +def strptime( + strings: _StringScalar | _ArrayOrChunkedArray | Expression, + /, + format: str, + unit: TimeUnit, + error_is_null: bool = False, + *, + options: StrptimeOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> TimestampScalar | TimestampArray | ChunkedArray | Expression: ... + +# ========================= 2.23 Temporal component extraction ========================= +def day( + values: _TemporalScalar | _ArrayOrChunkedArray | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> Int64Scalar | Int64Array | ChunkedArray | Expression: ... +def day_of_week( + values: _TemporalScalar | _ArrayOrChunkedArray | Expression, + /, + *, + count_from_zero: bool = True, + week_start: int = 1, + options: DayOfWeekOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> Int64Scalar | Int64Array | ChunkedArray | Expression: ... + +day_of_year = _clone_signature(day) + +def hour( + values: TimestampScalar + | Time32Scalar + | Time64Scalar + | _ArrayOrChunkedArray + | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> Int64Scalar | Int64Array | ChunkedArray | Expression: ... +def is_dst( + values: TimestampScalar | _ArrayOrChunkedArray | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> BooleanScalar | _BooleanArray | Expression: ... +def iso_week( + values: TimestampScalar | _ArrayOrChunkedArray | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> Int64Scalar | Int64Array | ChunkedArray | Expression: ... + +iso_year = _clone_signature(iso_week) + +def is_leap_year( + values: TimestampScalar + | Date32Scalar + | Date64Scalar + | _ArrayOrChunkedArray + | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> BooleanScalar | _BooleanArray | Expression: ... + +microsecond = _clone_signature(iso_week) +millisecond = _clone_signature(iso_week) +minute = _clone_signature(iso_week) +month = _clone_signature(day) +nanosecond = _clone_signature(hour) +quarter = _clone_signature(day) +second = _clone_signature(hour) +subsecond = _clone_signature(hour) +us_week = _clone_signature(iso_week) +us_year = _clone_signature(iso_week) +year = _clone_signature(iso_week) + +def week( + values: TimestampScalar | _ArrayOrChunkedArray | Expression, + /, + *, + week_starts_monday: bool = True, + count_from_zero: bool = False, + first_week_is_fully_in_year: bool = False, + options: WeekOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> Int64Scalar | Int64Array | ChunkedArray | Expression: ... +def year_month_day( + values: _TemporalScalar | _ArrayOrChunkedArray | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> StructScalar | StructArray | ChunkedArray | Expression: ... + +iso_calendar = _clone_signature(year_month_day) + +# ========================= 2.24 Temporal difference ========================= +def day_time_interval_between( + start: _TemporalScalar | _ArrayOrChunkedArray | Expression, + end: _TemporalScalar | _ArrayOrChunkedArray | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _ScalarOrArray | Expression: ... +def days_between( + start: _TemporalScalar | _ArrayOrChunkedArray | Expression, + end: _TemporalScalar | _ArrayOrChunkedArray | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> Int64Scalar | Int64Array | ChunkedArray | Expression: ... + +hours_between = _clone_signature(days_between) +microseconds_between = _clone_signature(days_between) +milliseconds_between = _clone_signature(days_between) +minutes_between = _clone_signature(days_between) + +def month_day_nano_interval_between( + start: _TemporalScalar | _ArrayOrChunkedArray | Expression, + end: _TemporalScalar | _ArrayOrChunkedArray | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> ( + MonthDayNanoIntervalScalar | MonthDayNanoIntervalArray | ChunkedArray | Expression +): ... +def month_interval_between( + start: _TemporalScalar | _ArrayOrChunkedArray | Expression, + end: _TemporalScalar | _ArrayOrChunkedArray | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _ScalarOrArray | Expression: ... + +nanoseconds_between = _clone_signature(days_between) +quarters_between = _clone_signature(days_between) +seconds_between = _clone_signature(days_between) + +def weeks_between( + start: _TemporalScalar | _ArrayOrChunkedArray | Expression, + end: _TemporalScalar | _ArrayOrChunkedArray | Expression, + /, + *, + count_from_zero: bool = True, + week_start: int = 1, + options: DayOfWeekOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> Int64Scalar | Int64Array | ChunkedArray | Expression: ... + +years_between = _clone_signature(days_between) + +# ========================= 2.25 Timezone handling ========================= + +def assume_timezone( + timestamps: TimestampScalar | _ArrayOrChunkedArray | Expression, + /, + timezone: str, + *, + ambiguous: Literal["raise", "earliest", "latest"] = "raise", + nonexistent: Literal["raise", "earliest", "latest"] = "raise", + options: AssumeTimezoneOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> TimestampScalar | TimestampArray | ChunkedArray | Expression: ... +def local_timestamp( + values: TimestampScalar | _ArrayOrChunkedArray | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> TimestampScalar | TimestampArray | ChunkedArray | Expression: ... + +# ========================= 2.26 Random number generation ========================= +def random( + n: int, + *, + initializer: Hashable = "system", + options: RandomOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> DoubleArray: ... + +# ========================= 3. Array-wise (“vector”) functions ========================= + +# ========================= 3.1 Cumulative Functions ========================= +def cumulative_sum( + values: _ArrayOrChunkedArray | ArrayLike | Expression, + /, + start: float | Scalar | None = None, + *, + skip_nulls: bool = False, + options: CumulativeOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _NumericArray | Expression: ... + +cumulative_sum_checked = _clone_signature(cumulative_sum) +cumulative_prod = _clone_signature(cumulative_sum) +cumulative_prod_checked = _clone_signature(cumulative_sum) +cumulative_max = _clone_signature(cumulative_sum) +cumulative_min = _clone_signature(cumulative_sum) +cumulative_mean = _clone_signature(cumulative_sum) +# ========================= 3.2 Associative transforms ========================= + +def dictionary_encode( + array: _ScalarOrArray | Expression, + /, + null_encoding: Literal["mask", "encode"] = "mask", + *, + options: DictionaryEncodeOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _ScalarOrArray | Expression: ... +def dictionary_decode( + dictionary_array: _ScalarOrArray | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _ScalarOrArray | Expression: ... +def unique( + array: _ArrayOrChunkedArray | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _ArrayOrChunkedArray | Expression: ... +def value_counts( + array: _ArrayOrChunkedArray | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> StructArray | Expression: ... + +# ========================= 3.3 Selections ========================= + +def array_filter( + array: _ArrayOrChunkedArray | Expression, + selection_filter: Mask | Expression, + /, + null_selection_behavior: Literal["drop", "emit_null"] = "drop", + *, + options: FilterOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _ArrayOrChunkedArray | Expression: ... +def drop_null( + input: _ArrayOrChunkedArray | RecordBatch | Table | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _ArrayOrChunkedArray | RecordBatch | Table | Expression: ... +def filter( + input: _ArrayOrChunkedArray | RecordBatch | Table | Expression, + selection_filter: Mask | Expression, + /, + null_selection_behavior: Literal["drop", "emit_null"] = "drop", + *, + options: FilterOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _ArrayOrChunkedArray | RecordBatch | Table | Expression: ... +def inverse_permutation( + indices: _ArrayOrChunkedArray | Expression, + /, + max_index: int = -1, + output_type: DataType | None = None, + *, + options: InversePermutationOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _IntegerArray | Expression: ... +def scatter( + values: _ArrayOrChunkedArray | Expression, + indices: _ArrayOrChunkedArray | Expression, + /, + max_index: int = -1, + *, + options: ScatterOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _ArrayOrChunkedArray | Expression: ... +def take( + data: _ArrayOrChunkedArray | RecordBatch | Table, + indices: Indices, + *, + boundscheck: bool = True, + memory_pool: MemoryPool | None = None, +) -> _ArrayOrChunkedArray | RecordBatch | Table: ... + +# ========================= 3.4 Containment tests ========================= + +def indices_nonzero( + values: _ArrayOrChunkedArray | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> UInt64Array | Expression: ... + +# ========================= 3.5 Sorts and partitions ========================= +def array_sort_indices( + array: _ArrayOrChunkedArray | Expression, + /, + order: Order = "ascending", + *, + null_placement: NullPlacement = "at_end", + options: ArraySortOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> UInt64Array | Expression: ... +def partition_nth_indices( + array: _ArrayOrChunkedArray | Iterable[Any] | Expression, + /, + pivot: int, + *, + null_placement: NullPlacement = "at_end", + options: PartitionNthOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> UInt64Array | Expression: ... +def pivot_wider( + pivot_keys: _ArrayOrChunkedArray | Sequence[str], + pivot_values: _ArrayOrChunkedArray | Sequence[Any], + /, + key_names: Sequence[str], + *, + unexpected_key_behavior: Literal["ignore", "raise"] = "ignore", + options: PivotWiderOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> StructScalar: ... +def rank( + input: _ArrayOrChunkedArray, + /, + sort_keys: Order | Sequence[_SortKey] = "ascending", + *, + null_placement: NullPlacement | None = None, + tiebreaker: Literal["min", "max", "first", "dense"] = "first", + options: RankOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> UInt64Array: ... +def rank_quantile( + input: _ArrayOrChunkedArray, + /, + sort_keys: Order | Sequence[_SortKey] = "ascending", + *, + null_placement: NullPlacement | None = None, + options: RankQuantileOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> DoubleArray: ... +def rank_normal( + input: _ArrayOrChunkedArray, + /, + sort_keys: Order | Sequence[_SortKey] = "ascending", + *, + null_placement: NullPlacement | None = None, + options: RankQuantileOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> DoubleArray: ... +def select_k_unstable( + input: _ArrayOrChunkedArray | RecordBatch | Table | Expression, + /, + k: int, + sort_keys: Sequence[_SortKey], + *, + options: SelectKOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> UInt64Array | Expression: ... +def sort_indices( + input: _ArrayOrChunkedArray | RecordBatch | Table | Expression, + /, + sort_keys: Sequence[_SortKey] = (), + *, + null_placement: NullPlacement | None = None, + options: SortOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> UInt64Array | Expression: ... +def search_sorted( + values: _ArrayOrChunkedArray | Expression, + needles: _ScalarOrArray | ScalarLike | Expression, + /, + side: Literal["left", "right"] = "left", + *, + options: SearchSortedOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> UInt64Scalar | UInt64Array | ChunkedArray | Expression: ... + +# ========================= 3.6 Structural transforms ========================= +def list_element( + lists: _ListScalar | _ArrayOrChunkedArray | Expression, + index: int | _IntegerScalar | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _ScalarOrArray | Expression: ... +def list_flatten( + lists: _ArrayOrChunkedArray | Expression, + /, + recursive: bool = False, + *, + options: ListFlattenOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _ArrayOrChunkedArray | Expression: ... +def list_parent_indices( + lists: _ArrayOrChunkedArray | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> Int64Array | Expression: ... +def list_slice( + lists: _ArrayOrChunkedArray | Expression, + /, + start: int, + stop: int | None = None, + step: int = 1, + return_fixed_size_list: bool | None = None, + *, + options: ListSliceOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _ListArray | Expression: ... +def map_lookup( + container: _ScalarOrArray | Expression, + /, + query_key: ScalarLike, + occurrence: Literal["first", "last", "all"], + *, + options: MapLookupOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _ScalarOrArray | Expression: ... +def struct_field( + values: StructScalar | _ArrayOrChunkedArray | Expression, + /, + indices: Sequence[str | bytes | int] | Expression | bytes | str | int, + *, + options: StructFieldOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _ScalarOrArray | Expression: ... +def fill_null_backward( + values: _ScalarOrArray | ScalarLike | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _ScalarOrArray | ScalarLike | Expression: ... +def fill_null_forward( + values: _ScalarOrArray | ScalarLike | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _ScalarOrArray | ScalarLike | Expression: ... +def replace_with_mask( + values: _ScalarOrArray | Expression, + mask: Mask, + replacements: ArrayLike, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _ScalarOrArray | Expression: ... + +# ========================= 3.7 Pairwise functions ========================= +def pairwise_diff( + input: _ArrayOrChunkedArray | Expression, + /, + period: int = 1, + *, + options: PairwiseOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _NumericOrTemporalArray | Expression: ... +def run_end_encode( + array: _ArrayOrChunkedArray | Expression, + /, + run_end_type: DataType | str = ..., + *, + options: RunEndEncodeOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> RunEndEncodedArray | ChunkedArray | Expression: ... +def run_end_decode( + array: _ArrayOrChunkedArray | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _ArrayOrChunkedArray | Expression: ... + +pairwise_diff_checked = _clone_signature(pairwise_diff) diff --git a/python/pyproject.toml b/python/pyproject.toml index 1556354f6bd7..ff68f4ce24dc 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -123,7 +123,7 @@ warn_unused_ignores = true # Modules that will be annotated in later PRs (GH-32609). Treat them as Any # rather than type checking their sources. [[tool.mypy.overrides]] -module = ["pyarrow._compute", "pyarrow.compute", "pyarrow.interchange.*"] +module = ["pyarrow.interchange.*"] follow_imports = "skip" # Optional dependencies without type hints. @@ -154,8 +154,6 @@ reportMissingModuleSource = false # Modules that will be annotated in later PRs (GH-32609), and the optional # sparse dependency, which has no type hints. Treat them as Any. replace-imports-with-any = [ - "pyarrow._compute", - "pyarrow.compute", "pyarrow.interchange.**", "sparse", ] @@ -166,10 +164,15 @@ include = ["pyarrow-stubs", "pyarrow-stubs-tests"] # ty doesn't honor `# type: ignore[]` comments, so disable the # rules that those comments suppress for mypy. [[tool.ty.overrides]] -include = ["pyarrow-stubs/__lib/array.pyi", "pyarrow-stubs/__lib/scalar.pyi"] +include = [ + "pyarrow-stubs/__lib/array.pyi", + "pyarrow-stubs/__lib/scalar.pyi", + "pyarrow-stubs/_compute.pyi", +] [tool.ty.overrides.rules] # Some array and scalar classes override methods with a different signature at -# runtime. +# runtime, and Expression.__eq__ and __ne__ return an Expression rather than a +# bool. incompatible-method-override = "ignore" [[tool.ty.overrides]] From aa3e2465473760dca6c484da836cf97f5e85b14a Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Tue, 17 Nov 2026 06:19:33 +0100 Subject: [PATCH 03/33] Review changes of _acero.pyi --- python/pyarrow-stubs-tests/test_acero.py | 14 +++++++++++++- python/pyarrow-stubs/_acero.pyi | 2 +- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/python/pyarrow-stubs-tests/test_acero.py b/python/pyarrow-stubs-tests/test_acero.py index fe4e9500e9d0..44309f20b929 100644 --- a/python/pyarrow-stubs-tests/test_acero.py +++ b/python/pyarrow-stubs-tests/test_acero.py @@ -26,7 +26,11 @@ # PyArrow can be built without Acero. pytest.importorskip("pyarrow._acero") -from pyarrow._acero import Declaration, TableSourceNodeOptions # noqa: E402 +from pyarrow._acero import ( # noqa: E402 + AggregateNodeOptions, + Declaration, + TableSourceNodeOptions, +) def test_declaration() -> None: @@ -37,3 +41,11 @@ def test_declaration() -> None: if TYPE_CHECKING: TableSourceNodeOptions(table.to_batches()[0]) # type: ignore[arg-type] + + +def test_aggregate() -> None: + aggr_opts = AggregateNodeOptions([(["a"], "sum", None, "a_sum")]) + check(assert_type(aggr_opts, AggregateNodeOptions), AggregateNodeOptions) + + aggr_opts = AggregateNodeOptions([(("a", ), "sum", None, "a_sum")]) + check(assert_type(aggr_opts, AggregateNodeOptions), AggregateNodeOptions) diff --git a/python/pyarrow-stubs/_acero.pyi b/python/pyarrow-stubs/_acero.pyi index ca36550662f4..1f968965e52d 100644 --- a/python/pyarrow-stubs/_acero.pyi +++ b/python/pyarrow-stubs/_acero.pyi @@ -29,7 +29,7 @@ from pyarrow.compute import Expression _StrOrExpr: TypeAlias = str | Expression _IntoField: TypeAlias = str | int | Expression -_Target: TypeAlias = _IntoField | tuple[_IntoField, ...] | Sequence[_IntoField] +_Target: TypeAlias = _IntoField | Sequence[_IntoField] _Aggregate: TypeAlias = tuple[_Target, _AggregationName, _AggregateOptions | None, str] _SortKey: TypeAlias = ( tuple[str | Expression | int, Order] From f050038e615192206af4ea1c2b726a53226f17f5 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Tue, 17 Nov 2026 14:58:13 +0100 Subject: [PATCH 04/33] Review changes of _compute.pyi --- python/pyarrow-stubs-tests/test_compute.py | 36 +++++++ python/pyarrow-stubs/_acero.pyi | 8 +- python/pyarrow-stubs/_compute.pyi | 106 ++++++++++++--------- python/pyarrow-stubs/compute.pyi | 47 +++++---- python/pyarrow/_compute.pyx | 6 +- python/pyarrow/_substrait.pyx | 2 +- 6 files changed, 133 insertions(+), 72 deletions(-) diff --git a/python/pyarrow-stubs-tests/test_compute.py b/python/pyarrow-stubs-tests/test_compute.py index 2c03b7131d70..433dab100c98 100644 --- a/python/pyarrow-stubs-tests/test_compute.py +++ b/python/pyarrow-stubs-tests/test_compute.py @@ -63,6 +63,23 @@ def test_expression() -> None: pc.field(1.0) # type: ignore[arg-type] +def test_expression_substrait() -> None: + schema = pa.schema([("a", pa.int64())]) + message = pc.field("a").to_substrait(schema) + check(assert_type(message, memoryview), memoryview) + + expr = pc.Expression.from_substrait(message) + check(assert_type(expr, pc.Expression), pc.Expression) + + class Message: + def SerializeToString(self) -> bytes: + return bytes(message) + + check(pc.Expression.from_substrait(bytes(message)), pc.Expression) + check(pc.Expression.from_substrait(pa.py_buffer(message)), pc.Expression) + check(pc.Expression.from_substrait(Message()), pc.Expression) + + def test_functions() -> None: func = pc.get_function("sum") check(assert_type(func, pc.Function), pc.Function) @@ -73,6 +90,11 @@ def test_functions() -> None: check(assert_type(pc.function_registry(), pc.FunctionRegistry), pc.FunctionRegistry) + func = pc.get_function("add") + assert isinstance(func, pc.ScalarFunction) + check(assert_type(func.kernels, list[pc.ScalarKernel]), list) + check(assert_type(func.kernels[0], pc.ScalarKernel), pc.ScalarKernel) + def test_options() -> None: check(assert_type(pc.CastOptions.safe(pa.int64()), pc.CastOptions), @@ -84,6 +106,17 @@ def test_options() -> None: check(assert_type(pc.SortOptions([("a", "ascending", "at_start")]), pc.SortOptions), pc.SortOptions) + check(assert_type(pc.SortOptions([(0, "ascending", "at_start")]), + pc.SortOptions), + pc.SortOptions) + md = pa.KeyValueMetadata({"k": "v"}) + check(assert_type(pc.MakeStructOptions(["a", "b"], field_metadata=[None, md]), + pc.MakeStructOptions), + pc.MakeStructOptions) + check(assert_type(pc.StructFieldOptions((0, 1)), pc.StructFieldOptions), + pc.StructFieldOptions) + check(assert_type(pc.StructFieldOptions(["a", "b"]), pc.StructFieldOptions), + pc.StructFieldOptions) check(assert_type(pc.SelectKOptions(1, [("a", "ascending", "at_end")]), pc.SelectKOptions), pc.SelectKOptions) @@ -113,6 +146,9 @@ def test_array_functions() -> None: check(assert_type(pc.sort_indices(table, [("a", "descending")]), pa.UInt64Array | pc.Expression), pa.UInt64Array) + check(assert_type(pc.sort_indices(table, [(0, "descending")]), + pa.UInt64Array | pc.Expression), + pa.UInt64Array) check(assert_type(pc.top_k_unstable(arr, 2), pa.UInt64Array), pa.UInt64Array) check(assert_type(pc.bottom_k_unstable(table, 2, ["a"], ["at_end"]), pa.UInt64Array), diff --git a/python/pyarrow-stubs/_acero.pyi b/python/pyarrow-stubs/_acero.pyi index 1f968965e52d..b148ffe7f8d2 100644 --- a/python/pyarrow-stubs/_acero.pyi +++ b/python/pyarrow-stubs/_acero.pyi @@ -22,19 +22,17 @@ from typing import Literal, TypeAlias # when imported through pyarrow.lib. from pyarrow.__lib.ipc import RecordBatchReader from pyarrow.__lib.table import _AggregateOptions, _AggregationName -from pyarrow._stubs_typing import NullPlacement, Order +from pyarrow._stubs_typing import NullPlacement from pyarrow.lib import Table, _Weakrefable from pyarrow.compute import Expression +from pyarrow._compute import _SortKey _StrOrExpr: TypeAlias = str | Expression _IntoField: TypeAlias = str | int | Expression _Target: TypeAlias = _IntoField | Sequence[_IntoField] _Aggregate: TypeAlias = tuple[_Target, _AggregationName, _AggregateOptions | None, str] -_SortKey: TypeAlias = ( - tuple[str | Expression | int, Order] - | tuple[str | Expression | int, Order, NullPlacement] -) + _JoinType: TypeAlias = Literal[ "left semi", "right semi", diff --git a/python/pyarrow-stubs/_compute.pyi b/python/pyarrow-stubs/_compute.pyi index 8afc49c48749..c9befae94a8f 100644 --- a/python/pyarrow-stubs/_compute.pyi +++ b/python/pyarrow-stubs/_compute.pyi @@ -17,7 +17,7 @@ from collections.abc import Callable, Hashable, Iterable, Mapping, Sequence from types import EllipsisType -from typing import Any, ClassVar, Literal, TypeAlias, TypedDict +from typing import Any, ClassVar, Literal, Protocol, TypeAlias, TypedDict # Placeholders (Any) until ipc.pyi and scalar.pyi are annotated; mypy # rejects them as types when imported through pyarrow.lib. @@ -69,10 +69,18 @@ _DateTimeUnit: TypeAlias = Literal[ # Sort keys are (name, order) or (name, order, null_placement) tuples; the # null_placement arguments of the options are deprecated. _SortKey: TypeAlias = ( - tuple[str | Expression, Order] | tuple[str | Expression, Order, NullPlacement] + tuple[str | Expression | int, Order] + | tuple[str | Expression | int, Order, NullPlacement] ) _CountMode: TypeAlias = Literal["only_valid", "only_null", "all"] +_Form: TypeAlias = Literal["NFC", "NFKC", "NFD", "NFKD"] +_Interpolation: TypeAlias = Literal["linear", "lower", "higher", "nearest", "midpoint"] +_NullHandling: TypeAlias = Literal["emit_null", "skip", "replace"] +_Occurrence: TypeAlias = Literal["first", "last", "all"] +_Side: TypeAlias = Literal["left", "right"] +_Tiebreaker: TypeAlias = Literal["min", "max", "first", "dense"] _TimezoneResolution: TypeAlias = Literal["raise", "earliest", "latest"] +_UnexpectedKeyBehavior: TypeAlias = Literal["ignore", "raise"] class Kernel(_Weakrefable): ... @@ -106,13 +114,32 @@ class FunctionRegistry(_Weakrefable): def get_function(self, name: str) -> Function: ... def list_functions(self) -> list[str]: ... -class HashAggregateFunction(Function): ... +class HashAggregateFunction(Function): + @property + def kernels(self) -> list[HashAggregateKernel]: ... + class HashAggregateKernel(Kernel): ... -class ScalarAggregateFunction(Function): ... + +class MetaFunction(Function): + @property + def kernels(self) -> list[Kernel]: ... + +class ScalarAggregateFunction(Function): + @property + def kernels(self) -> list[ScalarAggregateKernel]: ... + class ScalarAggregateKernel(Kernel): ... -class ScalarFunction(Function): ... + +class ScalarFunction(Function): + @property + def kernels(self) -> list[ScalarKernel]: ... + class ScalarKernel(Kernel): ... -class VectorFunction(Function): ... + +class VectorFunction(Function): + @property + def kernels(self) -> list[VectorKernel]: ... + class VectorKernel(Kernel): ... # ==================== Option classes ==================== @@ -144,7 +171,7 @@ class CastOptions(FunctionOptions): def __init__( self, - target_type: DataType | None = None, + target_type: DataType | str | None = None, *, allow_int_overflow: bool | None = None, allow_time_truncate: bool | None = None, @@ -154,9 +181,9 @@ class CastOptions(FunctionOptions): allow_invalid_utf8: bool | None = None, ) -> None: ... @staticmethod - def safe(target_type: DataType | None = None) -> CastOptions: ... + def safe(target_type: DataType | str | None = None) -> CastOptions: ... @staticmethod - def unsafe(target_type: DataType | None = None) -> CastOptions: ... + def unsafe(target_type: DataType | str | None = None) -> CastOptions: ... def is_safe(self) -> bool: ... class CountOptions(FunctionOptions): @@ -197,13 +224,13 @@ class IndexOptions(FunctionOptions): class InversePermutationOptions(FunctionOptions): def __init__( - self, max_index: int = -1, output_type: DataType | None = None + self, max_index: int = -1, output_type: DataType | str | None = None ) -> None: ... class JoinOptions(FunctionOptions): def __init__( self, - null_handling: Literal["emit_null", "skip", "replace"] = "emit_null", + null_handling: _NullHandling = "emit_null", null_replacement: str = "", ) -> None: ... @@ -225,13 +252,11 @@ class MakeStructOptions(FunctionOptions): field_names: Sequence[str] = (), *, field_nullability: Sequence[bool] | None = None, - field_metadata: Sequence[KeyValueMetadata] | None = None, + field_metadata: Sequence[KeyValueMetadata | None] | None = None, ) -> None: ... class MapLookupOptions(FunctionOptions): - def __init__( - self, query_key: Any, occurrence: Literal["first", "last", "all"] - ) -> None: ... + def __init__(self, query_key: Any, occurrence: _Occurrence) -> None: ... class MatchSubstringOptions(FunctionOptions): def __init__(self, pattern: str, *, ignore_case: bool = False) -> None: ... @@ -265,9 +290,7 @@ class QuantileOptions(FunctionOptions): self, q: float | Sequence[float] = 0.5, *, - interpolation: Literal[ - "linear", "lower", "higher", "nearest", "midpoint" - ] = "linear", + interpolation: _Interpolation = "linear", skip_nulls: bool = True, min_count: int = 0, ) -> None: ... @@ -281,7 +304,7 @@ class RankOptions(FunctionOptions): sort_keys: Order | Sequence[_SortKey] = "ascending", *, null_placement: NullPlacement | None = None, - tiebreaker: Literal["min", "max", "first", "dense"] = "first", + tiebreaker: _Tiebreaker = "first", ) -> None: ... class RankQuantileOptions(FunctionOptions): @@ -297,7 +320,7 @@ class PivotWiderOptions(FunctionOptions): self, key_names: Sequence[str], *, - unexpected_key_behavior: Literal["ignore", "raise"] = "ignore", + unexpected_key_behavior: _UnexpectedKeyBehavior = "ignore", ) -> None: ... class ReplaceSliceOptions(FunctionOptions): @@ -341,7 +364,7 @@ class ScatterOptions(FunctionOptions): def __init__(self, max_index: int = -1) -> None: ... class SearchSortedOptions(FunctionOptions): - def __init__(self, side: Literal["left", "right"] = "left") -> None: ... + def __init__(self, side: _Side = "left") -> None: ... class SelectKOptions(FunctionOptions): def __init__(self, k: int, sort_keys: Sequence[_SortKey]) -> None: ... @@ -406,7 +429,7 @@ class TrimOptions(FunctionOptions): def __init__(self, characters: str) -> None: ... class Utf8NormalizeOptions(FunctionOptions): - def __init__(self, form: Literal["NFC", "NFKC", "NFD", "NFKD"]) -> None: ... + def __init__(self, form: _Form) -> None: ... class VarianceOptions(FunctionOptions): def __init__( @@ -459,32 +482,32 @@ def register_scalar_function( func: Callable[..., Any], function_name: str, function_doc: _FunctionDoc | dict[str, str], - in_types: Mapping[str, DataType], - out_type: DataType, + in_types: Mapping[str, DataType | str], + out_type: DataType | str, func_registry: FunctionRegistry | None = None, ) -> None: ... def register_tabular_function( func: Callable[..., Any], function_name: str, function_doc: _FunctionDoc | dict[str, str], - in_types: Mapping[str, DataType], - out_type: DataType, + in_types: Mapping[str, DataType | str], + out_type: DataType | str, func_registry: FunctionRegistry | None = None, ) -> None: ... def register_aggregate_function( func: Callable[..., Any], function_name: str, function_doc: _FunctionDoc | dict[str, str], - in_types: Mapping[str, DataType], - out_type: DataType, + in_types: Mapping[str, DataType | str], + out_type: DataType | str, func_registry: FunctionRegistry | None = None, ) -> None: ... def register_vector_function( func: Callable[..., Any], function_name: str, function_doc: _FunctionDoc | dict[str, str], - in_types: Mapping[str, DataType], - out_type: DataType, + in_types: Mapping[str, DataType | str], + out_type: DataType | str, func_registry: FunctionRegistry | None = None, ) -> None: ... @@ -494,30 +517,21 @@ class UdfContext: @property def memory_pool(self) -> MemoryPool: ... -def _get_udf_context(memory_pool: MemoryPool, batch_length: int) -> UdfContext: ... - # ==================== Expression ==================== +class _SubstraitMessage(Protocol): + def SerializeToString(self) -> bytes: ... + class Expression(_Weakrefable): __hash__: ClassVar[None] # type: ignore[assignment] @staticmethod - def from_substrait(message: bytes | Buffer) -> Expression: ... + def from_substrait( + message: bytes | memoryview | Buffer | _SubstraitMessage, + ) -> Expression: ... def to_substrait( self, schema: Schema, allow_arrow_extensions: bool = False - ) -> Buffer: ... - @staticmethod - def _call( - function_name: str, - arguments: list[Any], - options: FunctionOptions | None = None, - ) -> Expression: ... - @staticmethod - def _field(name_or_idx: str | int) -> Expression: ... - @staticmethod - def _nested_field(names: tuple[str | int, ...]) -> Expression: ... - @staticmethod - def _scalar(value: Any) -> Expression: ... + ) -> memoryview: ... def __invert__(self) -> Expression: ... # The Expression must be the left operand: the reflected methods, e.g. # 1 + Expression, raise TypeError at runtime. diff --git a/python/pyarrow-stubs/compute.pyi b/python/pyarrow-stubs/compute.pyi index 827f123276cd..1ccc1578d37f 100644 --- a/python/pyarrow-stubs/compute.pyi +++ b/python/pyarrow-stubs/compute.pyi @@ -16,7 +16,7 @@ # under the License. from collections.abc import Callable, Hashable, Iterable, Sequence -from typing import Any, Literal, ParamSpec, TypeAlias, TypeVar +from typing import Any, ParamSpec, TypeAlias, TypeVar # Placeholders (Any) until scalar.pyi is annotated; mypy rejects them as # types when imported through pyarrow.lib. @@ -142,12 +142,27 @@ from pyarrow._compute import ( register_tabular_function as register_tabular_function, register_vector_function as register_vector_function, ) -from pyarrow._compute import _CountMode, _DateTimeUnit, _RoundMode, _SortKey +from pyarrow._compute import ( + _CountMode, + _DateTimeUnit, + _Form, + _Interpolation, + _NullHandling, + _Occurrence, + _RoundMode, + _Side, + _SortKey, + _Tiebreaker, + _TimezoneResolution, + _UnexpectedKeyBehavior, +) from pyarrow._stubs_typing import ( ArrayLike, Indices, Mask, + NullEncoding, NullPlacement, + NullSelectionBehavior, Order, ScalarLike, TimeUnit, @@ -395,9 +410,7 @@ def quantile( /, q: float | Sequence[float] = 0.5, *, - interpolation: Literal[ - "linear", "lower", "higher", "nearest", "midpoint" - ] = "linear", + interpolation: _Interpolation = "linear", skip_nulls: bool = True, min_count: int = 0, options: QuantileOptions | None = None, @@ -994,7 +1007,7 @@ def binary_join_element_wise( | _ArrayOrChunkedArray | Iterable[Any] | Expression, - null_handling: Literal["emit_null", "skip", "replace"] = "emit_null", + null_handling: _NullHandling = "emit_null", null_replacement: str = "", options: JoinOptions | None = None, memory_pool: MemoryPool | None = None, @@ -1024,7 +1037,7 @@ def utf8_slice_codeunits( def utf8_normalize( strings: _StringScalar | _ArrayOrChunkedArray | Expression, /, - form: Literal["NFC", "NFKC", "NFD", "NFKD"], + form: _Form, *, options: Utf8NormalizeOptions | None = None, memory_pool: MemoryPool | None = None, @@ -1359,8 +1372,8 @@ def assume_timezone( /, timezone: str, *, - ambiguous: Literal["raise", "earliest", "latest"] = "raise", - nonexistent: Literal["raise", "earliest", "latest"] = "raise", + ambiguous: _TimezoneResolution = "raise", + nonexistent: _TimezoneResolution = "raise", options: AssumeTimezoneOptions | None = None, memory_pool: MemoryPool | None = None, ) -> TimestampScalar | TimestampArray | ChunkedArray | Expression: ... @@ -1404,7 +1417,7 @@ cumulative_mean = _clone_signature(cumulative_sum) def dictionary_encode( array: _ScalarOrArray | Expression, /, - null_encoding: Literal["mask", "encode"] = "mask", + null_encoding: NullEncoding = "mask", *, options: DictionaryEncodeOptions | None = None, memory_pool: MemoryPool | None = None, @@ -1434,7 +1447,7 @@ def array_filter( array: _ArrayOrChunkedArray | Expression, selection_filter: Mask | Expression, /, - null_selection_behavior: Literal["drop", "emit_null"] = "drop", + null_selection_behavior: NullSelectionBehavior = "drop", *, options: FilterOptions | None = None, memory_pool: MemoryPool | None = None, @@ -1449,7 +1462,7 @@ def filter( input: _ArrayOrChunkedArray | RecordBatch | Table | Expression, selection_filter: Mask | Expression, /, - null_selection_behavior: Literal["drop", "emit_null"] = "drop", + null_selection_behavior: NullSelectionBehavior = "drop", *, options: FilterOptions | None = None, memory_pool: MemoryPool | None = None, @@ -1458,7 +1471,7 @@ def inverse_permutation( indices: _ArrayOrChunkedArray | Expression, /, max_index: int = -1, - output_type: DataType | None = None, + output_type: DataType | str | None = None, *, options: InversePermutationOptions | None = None, memory_pool: MemoryPool | None = None, @@ -1514,7 +1527,7 @@ def pivot_wider( /, key_names: Sequence[str], *, - unexpected_key_behavior: Literal["ignore", "raise"] = "ignore", + unexpected_key_behavior: _UnexpectedKeyBehavior = "ignore", options: PivotWiderOptions | None = None, memory_pool: MemoryPool | None = None, ) -> StructScalar: ... @@ -1524,7 +1537,7 @@ def rank( sort_keys: Order | Sequence[_SortKey] = "ascending", *, null_placement: NullPlacement | None = None, - tiebreaker: Literal["min", "max", "first", "dense"] = "first", + tiebreaker: _Tiebreaker = "first", options: RankOptions | None = None, memory_pool: MemoryPool | None = None, ) -> UInt64Array: ... @@ -1568,7 +1581,7 @@ def search_sorted( values: _ArrayOrChunkedArray | Expression, needles: _ScalarOrArray | ScalarLike | Expression, /, - side: Literal["left", "right"] = "left", + side: _Side = "left", *, options: SearchSortedOptions | None = None, memory_pool: MemoryPool | None = None, @@ -1611,7 +1624,7 @@ def map_lookup( container: _ScalarOrArray | Expression, /, query_key: ScalarLike, - occurrence: Literal["first", "last", "all"], + occurrence: _Occurrence, *, options: MapLookupOptions | None = None, memory_pool: MemoryPool | None = None, diff --git a/python/pyarrow/_compute.pyx b/python/pyarrow/_compute.pyx index 789e710875e7..5290b87730e7 100644 --- a/python/pyarrow/_compute.pyx +++ b/python/pyarrow/_compute.pyx @@ -1770,7 +1770,7 @@ class SetLookupOptions(_SetLookupOptions): Parameters ---------- - value_set : Array + value_set : Array, ChunkedArray or Scalar Set of values to look for in the input. skip_nulls : bool, default False If False, nulls in the input are matched in the value_set just @@ -2751,8 +2751,8 @@ cdef class Expression(_Weakrefable): Returns ------- - Buffer - A buffer containing the serialized Protobuf plan. + memoryview + A memoryview buffer containing the serialized Protobuf plan. """ return _pas().serialize_expressions([self], ["expression"], schema, allow_arrow_extensions=allow_arrow_extensions) diff --git a/python/pyarrow/_substrait.pyx b/python/pyarrow/_substrait.pyx index d9359c8e77d0..cd0d011caef6 100644 --- a/python/pyarrow/_substrait.pyx +++ b/python/pyarrow/_substrait.pyx @@ -323,7 +323,7 @@ def serialize_expressions(exprs, names, schema, *, allow_arrow_extensions=False) Returns ------- - Buffer + memoryview An ExtendedExpression message containing the serialized expressions """ cdef: From 29f167380f1e944723523f5d277bd682f537660c Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Wed, 18 Nov 2026 15:52:15 +0100 Subject: [PATCH 05/33] Order compute.pyi to match C++ docs --- python/pyarrow-stubs/compute.pyi | 223 ++++++++++++++++--------------- 1 file changed, 114 insertions(+), 109 deletions(-) diff --git a/python/pyarrow-stubs/compute.pyi b/python/pyarrow-stubs/compute.pyi index 1ccc1578d37f..ee11780186bf 100644 --- a/python/pyarrow-stubs/compute.pyi +++ b/python/pyarrow-stubs/compute.pyi @@ -292,19 +292,7 @@ _TemporalArray: TypeAlias = ( ) _ListArray: TypeAlias = BaseListArray | ChunkedArray -# =============================== 1. Aggregation =============================== - -def array_take( - array: _ArrayOrChunkedArray | RecordBatch | Table | Expression, - indices: Indices | Expression, - /, - *, - boundscheck: bool = True, - options: TakeOptions | None = None, - memory_pool: MemoryPool | None = None, -) -> _ArrayOrChunkedArray | RecordBatch | Table | Expression: ... - -# ========================= 1.1 functions ========================= +# =============================== Aggregations ======================================== def all( array: BooleanScalar | _ArrayOrChunkedArray | Expression, @@ -457,15 +445,6 @@ def variance( options: VarianceOptions | None = None, memory_pool: MemoryPool | None = None, ) -> DoubleScalar | Expression: ... -def winsorize( - array: _ArrayOrChunkedArray | Expression, - /, - lower_limit: float, - upper_limit: float, - *, - options: WinsorizeOptions | None = None, - memory_pool: MemoryPool | None = None, -) -> _NumericArray | Expression: ... def skew( array: _NumericScalar | _ArrayOrChunkedArray | ArrayLike | Expression, /, @@ -486,26 +465,20 @@ def kurtosis( options: SkewOptions | None = None, memory_pool: MemoryPool | None = None, ) -> DoubleScalar | Expression: ... -def top_k_unstable( - values: _ArrayOrChunkedArray | RecordBatch | Table, - k: int, - sort_keys: Sequence[str] | None = None, - null_placements: Sequence[NullPlacement] | None = None, - *, - memory_pool: MemoryPool | None = None, -) -> UInt64Array: ... -def bottom_k_unstable( - values: _ArrayOrChunkedArray | RecordBatch | Table, - k: int, - sort_keys: Sequence[str] | None = None, - null_placements: Sequence[NullPlacement] | None = None, +def pivot_wider( + pivot_keys: _ArrayOrChunkedArray | Sequence[str], + pivot_values: _ArrayOrChunkedArray | Sequence[Any], + /, + key_names: Sequence[str], *, + unexpected_key_behavior: _UnexpectedKeyBehavior = "ignore", + options: PivotWiderOptions | None = None, memory_pool: MemoryPool | None = None, -) -> UInt64Array: ... +) -> StructScalar: ... -# ========================= 2. Element-wise (“scalar”) functions ========= +# =============================== Element-wise ("scalar") functions =================== -# ========================= 2.1 Arithmetic ========================= +# ========================= Arithmetic functions ========================= def abs( x: _NumericOrDurationScalar | _ArrayOrChunkedArray | Expression | float, /, @@ -606,7 +579,7 @@ sqrt_checked = _clone_signature(sqrt) subtract = _clone_signature(add) subtract_checked = _clone_signature(add) -# ========================= 2.1 Bit-wise functions ========================= +# ========================= Bit-wise functions ========================= def bit_wise_and( x: _NumericScalar | _ArrayOrChunkedArray | Expression | float, @@ -629,7 +602,7 @@ shift_left_checked = _clone_signature(bit_wise_and) shift_right = _clone_signature(bit_wise_and) shift_right_checked = _clone_signature(bit_wise_and) -# ========================= 2.2 Rounding functions ========================= +# ========================= Rounding functions ========================= def ceil( x: _FloatScalar | _ArrayOrChunkedArray | Expression | float, @@ -670,7 +643,7 @@ def round_binary( trunc = _clone_signature(ceil) -# ========================= 2.3 Logarithmic functions ========================= +# ========================= Logarithmic functions ========================= def ln( x: _NumericScalar | _ArrayOrChunkedArray | Expression | float, @@ -697,26 +670,18 @@ def logb( logb_checked = _clone_signature(logb) -# ========================= 2.4 Trigonometric functions ========================= +# ========================= Trigonometric functions ========================= acos = _clone_signature(ln) acos_checked = _clone_signature(ln) -acosh = _clone_signature(ln) -acosh_checked = _clone_signature(ln) asin = _clone_signature(ln) asin_checked = _clone_signature(ln) -asinh = _clone_signature(ln) atan = _clone_signature(ln) -atanh_checked = _clone_signature(ln) -atanh = _clone_signature(ln) cos = _clone_signature(ln) cos_checked = _clone_signature(ln) -cosh = _clone_signature(ln) sin = _clone_signature(ln) sin_checked = _clone_signature(ln) -sinh = _clone_signature(ln) tan = _clone_signature(ln) tan_checked = _clone_signature(ln) -tanh = _clone_signature(ln) def atan2( y: _NumericScalar | _ArrayOrChunkedArray | float | Expression, @@ -726,7 +691,17 @@ def atan2( memory_pool: MemoryPool | None = None, ) -> _FloatScalar | _FloatArray | Expression: ... -# ========================= 2.5 Comparisons functions ========================= +# ========================= Hyperbolic trigonometric functions ========================= +acosh = _clone_signature(ln) +acosh_checked = _clone_signature(ln) +asinh = _clone_signature(ln) +atanh_checked = _clone_signature(ln) +atanh = _clone_signature(ln) +cosh = _clone_signature(ln) +sinh = _clone_signature(ln) +tanh = _clone_signature(ln) + +# ========================= Comparisons ========================= def equal( x: _ScalarOrArray | ScalarLike | Expression, y: _ScalarOrArray | ScalarLike | Expression, @@ -750,7 +725,7 @@ def max_element_wise( min_element_wise = _clone_signature(max_element_wise) -# ========================= 2.6 Logical functions ========================= +# ========================= Logical functions ========================= def and_( x: BooleanScalar | _ArrayOrChunkedArray | bool | Expression, @@ -774,7 +749,7 @@ def invert( memory_pool: MemoryPool | None = None, ) -> BooleanScalar | _BooleanArray | Expression: ... -# ========================= 2.10 String predicates ========================= +# ========================= String predicates ========================= def ascii_is_alnum( strings: _StringScalar | _ArrayOrChunkedArray | Expression, /, @@ -801,7 +776,7 @@ ascii_is_title = _clone_signature(ascii_is_alnum) utf8_is_title = _clone_signature(ascii_is_alnum) string_is_ascii = _clone_signature(ascii_is_alnum) -# ========================= 2.11 String transforms ========================= +# ========================= String transforms ========================= def ascii_capitalize( strings: _StringScalar | _ArrayOrChunkedArray | Expression, @@ -893,7 +868,16 @@ utf8_swapcase = _clone_signature(utf8_capitalize) utf8_title = _clone_signature(utf8_capitalize) utf8_upper = _clone_signature(utf8_capitalize) -# ========================= 2.12 String padding ========================= +def utf8_normalize( + strings: _StringScalar | _ArrayOrChunkedArray | Expression, + /, + form: _Form, + *, + options: Utf8NormalizeOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _StringScalar | _StringArray | Expression: ... + +# ========================= String padding ========================= def ascii_center( strings: _StringScalar | _ArrayOrChunkedArray | Expression, @@ -924,7 +908,7 @@ def utf8_zero_fill( utf8_zfill = utf8_zero_fill -# ========================= 2.13 String trimming ========================= +# ========================= String trimming ========================= def ascii_ltrim( strings: _StringScalar | _ArrayOrChunkedArray | Expression, @@ -954,7 +938,7 @@ utf8_ltrim_whitespace = _clone_signature(ascii_ltrim_whitespace) utf8_rtrim_whitespace = _clone_signature(ascii_ltrim_whitespace) utf8_trim_whitespace = _clone_signature(ascii_ltrim_whitespace) -# ========================= 2.14 String splitting ========================= +# ========================= String splitting ========================= def ascii_split_whitespace( strings: _StringScalar | _ArrayOrChunkedArray | Expression, @@ -979,7 +963,7 @@ def split_pattern( split_pattern_regex = _clone_signature(split_pattern) utf8_split_whitespace = _clone_signature(ascii_split_whitespace) -# ========================= 2.15 String component extraction ========================= +# ========================= String component extraction ========================= def extract_regex( strings: _StringOrBinaryScalar | _ArrayOrChunkedArray | Expression, @@ -992,7 +976,7 @@ def extract_regex( extract_regex_span = _clone_signature(extract_regex) -# ========================= 2.16 String join ========================= +# ========================= String joining ========================= def binary_join( strings: _ListScalar | _ArrayOrChunkedArray | Expression, separator: str | bytes | _StringOrBinaryScalar | _ArrayOrChunkedArray | Expression, @@ -1013,7 +997,7 @@ def binary_join_element_wise( memory_pool: MemoryPool | None = None, ) -> _StringOrBinaryScalar | _StringOrBinaryArray | Expression: ... -# ========================= 2.17 String Slicing ========================= +# ========================= String Slicing ========================= def binary_slice( strings: _BinaryScalar | _ArrayOrChunkedArray | Expression, /, @@ -1034,16 +1018,8 @@ def utf8_slice_codeunits( options: SliceOptions | None = None, memory_pool: MemoryPool | None = None, ) -> _StringScalar | _StringArray | Expression: ... -def utf8_normalize( - strings: _StringScalar | _ArrayOrChunkedArray | Expression, - /, - form: _Form, - *, - options: Utf8NormalizeOptions | None = None, - memory_pool: MemoryPool | None = None, -) -> _StringScalar | _StringArray | Expression: ... -# ========================= 2.18 Containment tests ========================= +# ========================= Containment tests ========================= def count_substring( strings: _StringOrBinaryScalar | _ArrayOrChunkedArray | Expression, /, @@ -1103,7 +1079,7 @@ match_substring = _clone_signature(ends_with) match_substring_regex = _clone_signature(ends_with) starts_with = _clone_signature(ends_with) -# ========================= 2.19 Categorizations ========================= +# ========================= Categorizations ========================= def is_finite( values: _NumericScalar | NullScalar | _ArrayOrChunkedArray | Expression, @@ -1132,7 +1108,7 @@ def is_valid( true_unless_null = _clone_signature(is_valid) -# ========================= 2.20 Selecting / multiplexing ========================= +# ========================= Selecting / multiplexing ========================= def case_when( cond: StructScalar | _ArrayOrChunkedArray | Expression, @@ -1161,7 +1137,7 @@ def if_else( memory_pool: MemoryPool | None = None, ) -> ArrayLike | ScalarLike: ... -# ========================= 2.21 Structural transforms ========================= +# ========================= Structural transforms ========================= def list_value_length( lists: _ArrayOrChunkedArray | Expression, @@ -1180,7 +1156,7 @@ def make_struct( memory_pool: MemoryPool | None = None, ) -> StructScalar | StructArray | ChunkedArray | Expression: ... -# ========================= 2.22 Conversions ========================= +# ========================= Conversions ========================= def ceil_temporal( timestamps: _TemporalScalar | _ArrayOrChunkedArray | Expression, /, @@ -1223,8 +1199,22 @@ def strptime( options: StrptimeOptions | None = None, memory_pool: MemoryPool | None = None, ) -> TimestampScalar | TimestampArray | ChunkedArray | Expression: ... +def run_end_encode( + array: _ArrayOrChunkedArray | Expression, + /, + run_end_type: DataType | str = ..., + *, + options: RunEndEncodeOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> RunEndEncodedArray | ChunkedArray | Expression: ... +def run_end_decode( + array: _ArrayOrChunkedArray | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _ArrayOrChunkedArray | Expression: ... -# ========================= 2.23 Temporal component extraction ========================= +# ========================= Temporal component extraction ========================= def day( values: _TemporalScalar | _ArrayOrChunkedArray | Expression, /, @@ -1310,7 +1300,7 @@ def year_month_day( iso_calendar = _clone_signature(year_month_day) -# ========================= 2.24 Temporal difference ========================= +# ========================= Temporal difference ========================= def day_time_interval_between( start: _TemporalScalar | _ArrayOrChunkedArray | Expression, end: _TemporalScalar | _ArrayOrChunkedArray | Expression, @@ -1365,7 +1355,7 @@ def weeks_between( years_between = _clone_signature(days_between) -# ========================= 2.25 Timezone handling ========================= +# ========================= Timezone handling ========================= def assume_timezone( timestamps: TimestampScalar | _ArrayOrChunkedArray | Expression, @@ -1384,7 +1374,7 @@ def local_timestamp( memory_pool: MemoryPool | None = None, ) -> TimestampScalar | TimestampArray | ChunkedArray | Expression: ... -# ========================= 2.26 Random number generation ========================= +# ========================= Random number generation ========================= def random( n: int, *, @@ -1393,9 +1383,9 @@ def random( memory_pool: MemoryPool | None = None, ) -> DoubleArray: ... -# ========================= 3. Array-wise (“vector”) functions ========================= +# =============================== Array-wise ("vector") functions ===================== -# ========================= 3.1 Cumulative Functions ========================= +# ========================= Cumulative Functions ========================= def cumulative_sum( values: _ArrayOrChunkedArray | ArrayLike | Expression, /, @@ -1412,7 +1402,19 @@ cumulative_prod_checked = _clone_signature(cumulative_sum) cumulative_max = _clone_signature(cumulative_sum) cumulative_min = _clone_signature(cumulative_sum) cumulative_mean = _clone_signature(cumulative_sum) -# ========================= 3.2 Associative transforms ========================= + +# ========================= Statistical functions ========================= +def winsorize( + array: _ArrayOrChunkedArray | Expression, + /, + lower_limit: float, + upper_limit: float, + *, + options: WinsorizeOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _NumericArray | Expression: ... + +# ========================= Associative transforms ========================= def dictionary_encode( array: _ScalarOrArray | Expression, @@ -1441,7 +1443,7 @@ def value_counts( memory_pool: MemoryPool | None = None, ) -> StructArray | Expression: ... -# ========================= 3.3 Selections ========================= +# ========================= Selections ========================= def array_filter( array: _ArrayOrChunkedArray | Expression, @@ -1452,6 +1454,15 @@ def array_filter( options: FilterOptions | None = None, memory_pool: MemoryPool | None = None, ) -> _ArrayOrChunkedArray | Expression: ... +def array_take( + array: _ArrayOrChunkedArray | RecordBatch | Table | Expression, + indices: Indices | Expression, + /, + *, + boundscheck: bool = True, + options: TakeOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _ArrayOrChunkedArray | RecordBatch | Table | Expression: ... def drop_null( input: _ArrayOrChunkedArray | RecordBatch | Table | Expression, /, @@ -1493,7 +1504,7 @@ def take( memory_pool: MemoryPool | None = None, ) -> _ArrayOrChunkedArray | RecordBatch | Table: ... -# ========================= 3.4 Containment tests ========================= +# ========================= Containment tests ========================= def indices_nonzero( values: _ArrayOrChunkedArray | Expression, @@ -1502,7 +1513,7 @@ def indices_nonzero( memory_pool: MemoryPool | None = None, ) -> UInt64Array | Expression: ... -# ========================= 3.5 Sorts and partitions ========================= +# ========================= Sorts and partitions ========================= def array_sort_indices( array: _ArrayOrChunkedArray | Expression, /, @@ -1521,16 +1532,6 @@ def partition_nth_indices( options: PartitionNthOptions | None = None, memory_pool: MemoryPool | None = None, ) -> UInt64Array | Expression: ... -def pivot_wider( - pivot_keys: _ArrayOrChunkedArray | Sequence[str], - pivot_values: _ArrayOrChunkedArray | Sequence[Any], - /, - key_names: Sequence[str], - *, - unexpected_key_behavior: _UnexpectedKeyBehavior = "ignore", - options: PivotWiderOptions | None = None, - memory_pool: MemoryPool | None = None, -) -> StructScalar: ... def rank( input: _ArrayOrChunkedArray, /, @@ -1586,8 +1587,24 @@ def search_sorted( options: SearchSortedOptions | None = None, memory_pool: MemoryPool | None = None, ) -> UInt64Scalar | UInt64Array | ChunkedArray | Expression: ... +def top_k_unstable( + values: _ArrayOrChunkedArray | RecordBatch | Table, + k: int, + sort_keys: Sequence[str] | None = None, + null_placements: Sequence[NullPlacement] | None = None, + *, + memory_pool: MemoryPool | None = None, +) -> UInt64Array: ... +def bottom_k_unstable( + values: _ArrayOrChunkedArray | RecordBatch | Table, + k: int, + sort_keys: Sequence[str] | None = None, + null_placements: Sequence[NullPlacement] | None = None, + *, + memory_pool: MemoryPool | None = None, +) -> UInt64Array: ... -# ========================= 3.6 Structural transforms ========================= +# ========================= Structural transforms ========================= def list_element( lists: _ListScalar | _ArrayOrChunkedArray | Expression, index: int | _IntegerScalar | Expression, @@ -1637,6 +1654,8 @@ def struct_field( options: StructFieldOptions | None = None, memory_pool: MemoryPool | None = None, ) -> _ScalarOrArray | Expression: ... + +# ========================= Replace functions ========================= def fill_null_backward( values: _ScalarOrArray | ScalarLike | Expression, /, @@ -1658,7 +1677,7 @@ def replace_with_mask( memory_pool: MemoryPool | None = None, ) -> _ScalarOrArray | Expression: ... -# ========================= 3.7 Pairwise functions ========================= +# ========================= Pairwise functions ========================= def pairwise_diff( input: _ArrayOrChunkedArray | Expression, /, @@ -1667,19 +1686,5 @@ def pairwise_diff( options: PairwiseOptions | None = None, memory_pool: MemoryPool | None = None, ) -> _NumericOrTemporalArray | Expression: ... -def run_end_encode( - array: _ArrayOrChunkedArray | Expression, - /, - run_end_type: DataType | str = ..., - *, - options: RunEndEncodeOptions | None = None, - memory_pool: MemoryPool | None = None, -) -> RunEndEncodedArray | ChunkedArray | Expression: ... -def run_end_decode( - array: _ArrayOrChunkedArray | Expression, - /, - *, - memory_pool: MemoryPool | None = None, -) -> _ArrayOrChunkedArray | Expression: ... pairwise_diff_checked = _clone_signature(pairwise_diff) From f047bf7c1cc5dd76f5682dbe8f2079a91df32961 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Thu, 19 Nov 2026 10:15:43 +0100 Subject: [PATCH 06/33] Remove ArrayLike import and define _ArrayLike --- python/pyarrow-stubs-tests/test_compute.py | 11 ++++++ python/pyarrow-stubs/compute.pyi | 46 ++++++++++++---------- 2 files changed, 37 insertions(+), 20 deletions(-) diff --git a/python/pyarrow-stubs-tests/test_compute.py b/python/pyarrow-stubs-tests/test_compute.py index 433dab100c98..569c7517e496 100644 --- a/python/pyarrow-stubs-tests/test_compute.py +++ b/python/pyarrow-stubs-tests/test_compute.py @@ -182,6 +182,16 @@ def test_array_functions() -> None: check(pc.round([1.5, 2.5]), pa.Array) check(pc.binary_join_element_wise(["a", "b"], ["c", "d"], "-"), pa.Array) + import numpy as np + check(pc.variance([1, 2, 3]), pa.DoubleScalar) + check(pc.variance((1, 2, 3)), pa.DoubleScalar) + check(pc.variance(np.array([1.0, 2.0, 3.0])), pa.DoubleScalar) + + selected = pc.if_else([True, False], [1, 2], [3, 4]) + check(assert_type(selected, pa.Scalar | pa.Array | pa.ChunkedArray | pc.Expression), + pa.Array) + check(pc.if_else(pc.field("a") > 1, 1, 2), pc.Expression) + # Python literals are accepted next to arrays. check(pc.power(arr, 2), pa.Array) check(pc.divide(arr, 2.0), pa.Array) @@ -193,3 +203,4 @@ def test_array_functions() -> None: if TYPE_CHECKING: pc.top_k_unstable(arr, "2") # type: ignore[arg-type] pc.sort_indices(table, [("a", "up")]) # type: ignore[list-item] + pc.cumulative_sum(range(3)) # type: ignore[arg-type] diff --git a/python/pyarrow-stubs/compute.pyi b/python/pyarrow-stubs/compute.pyi index ee11780186bf..525e0d8052c1 100644 --- a/python/pyarrow-stubs/compute.pyi +++ b/python/pyarrow-stubs/compute.pyi @@ -18,6 +18,8 @@ from collections.abc import Callable, Hashable, Iterable, Sequence from typing import Any, ParamSpec, TypeAlias, TypeVar +from numpy.typing import NDArray + # Placeholders (Any) until scalar.pyi is annotated; mypy rejects them as # types when imported through pyarrow.lib. from pyarrow.__lib.scalar import ( @@ -157,7 +159,6 @@ from pyarrow._compute import ( _UnexpectedKeyBehavior, ) from pyarrow._stubs_typing import ( - ArrayLike, Indices, Mask, NullEncoding, @@ -259,6 +260,9 @@ _NumericOrTemporalScalar: TypeAlias = _NumericScalar | _TemporalScalar # chunked input is the same for every kind. _ArrayOrChunkedArray: TypeAlias = Array | ChunkedArray _ScalarOrArray: TypeAlias = Scalar | Array | ChunkedArray +_ArrayLike: TypeAlias = ( + list[Any] | tuple[Any, ...] | NDArray[Any] | Array | ChunkedArray +) _DecimalArray: TypeAlias = ( Decimal32Array | Decimal64Array | Decimal128Array | Decimal256Array ) @@ -436,7 +440,7 @@ def tdigest( memory_pool: MemoryPool | None = None, ) -> DoubleArray | Expression: ... def variance( - array: _NumericScalar | _ArrayOrChunkedArray | ArrayLike | Expression, + array: _NumericScalar | _ArrayOrChunkedArray | _ArrayLike | Expression, /, *, ddof: int = 0, @@ -446,7 +450,7 @@ def variance( memory_pool: MemoryPool | None = None, ) -> DoubleScalar | Expression: ... def skew( - array: _NumericScalar | _ArrayOrChunkedArray | ArrayLike | Expression, + array: _NumericScalar | _ArrayOrChunkedArray | _ArrayLike | Expression, /, *, skip_nulls: bool = True, @@ -456,7 +460,7 @@ def skew( memory_pool: MemoryPool | None = None, ) -> DoubleScalar | Expression: ... def kurtosis( - array: _NumericScalar | _ArrayOrChunkedArray | ArrayLike | Expression, + array: _NumericScalar | _ArrayOrChunkedArray | _ArrayLike | Expression, /, *, skip_nulls: bool = True, @@ -489,8 +493,10 @@ def abs( abs_checked = _clone_signature(abs) def add( - x: _NumericOrTemporalScalar | _ArrayOrChunkedArray | ArrayLike | int | Expression, - y: (_NumericOrTemporalScalar | _ArrayOrChunkedArray | ArrayLike | int | Expression), + x: _NumericOrTemporalScalar | _ArrayOrChunkedArray | _ArrayLike | int | Expression, + y: ( + _NumericOrTemporalScalar | _ArrayOrChunkedArray | _ArrayLike | int | Expression + ), /, *, memory_pool: MemoryPool | None = None, @@ -717,7 +723,7 @@ less_equal = _clone_signature(equal) not_equal = _clone_signature(equal) def max_element_wise( - *args: _ScalarOrArray | Expression | ScalarLike | ArrayLike, + *args: _ScalarOrArray | Expression | ScalarLike | _ArrayLike, skip_nulls: bool = True, options: ElementWiseAggregateOptions | None = None, memory_pool: MemoryPool | None = None, @@ -1100,7 +1106,7 @@ def is_null( memory_pool: MemoryPool | None = None, ) -> BooleanScalar | _BooleanArray | Expression: ... def is_valid( - values: _ScalarOrArray | Expression | ArrayLike, + values: _ScalarOrArray | Expression | _ArrayLike, /, *, memory_pool: MemoryPool | None = None, @@ -1113,29 +1119,29 @@ true_unless_null = _clone_signature(is_valid) def case_when( cond: StructScalar | _ArrayOrChunkedArray | Expression, /, - *cases: _ScalarOrArray | ArrayLike, + *cases: _ScalarOrArray | _ArrayLike, memory_pool: MemoryPool | None = None, ) -> _ScalarOrArray | Array | Expression: ... def choose( - indices: ArrayLike | ScalarLike, + indices: _ArrayLike | ScalarLike | Expression, /, - *values: ArrayLike | ScalarLike, + *values: _ArrayLike | ScalarLike, memory_pool: MemoryPool | None = None, -) -> ArrayLike | ScalarLike: ... +) -> _ScalarOrArray | Expression: ... def coalesce( *values: _ScalarOrArray | Expression, memory_pool: MemoryPool | None = None ) -> _ScalarOrArray | Expression: ... def fill_null( - values: _ScalarOrArray | ScalarLike, fill_value: ArrayLike | ScalarLike + values: _ScalarOrArray | ScalarLike, fill_value: _ArrayLike | ScalarLike ) -> _ScalarOrArray | ScalarLike: ... def if_else( - cond: ArrayLike | ScalarLike, - left: ArrayLike | ScalarLike, - right: ArrayLike | ScalarLike, + cond: _ArrayLike | ScalarLike | Expression, + left: _ArrayLike | ScalarLike, + right: _ArrayLike | ScalarLike, /, *, memory_pool: MemoryPool | None = None, -) -> ArrayLike | ScalarLike: ... +) -> _ScalarOrArray | Expression: ... # ========================= Structural transforms ========================= @@ -1148,7 +1154,7 @@ def list_value_length( Int32Scalar | Int64Scalar | Int32Array | Int64Array | ChunkedArray | Expression ): ... def make_struct( - *args: _ScalarOrArray | Expression | ArrayLike, + *args: _ScalarOrArray | Expression | _ArrayLike, field_names: Sequence[str] = (), field_nullability: bool | None = None, field_metadata: Sequence[KeyValueMetadata] | None = None, @@ -1387,7 +1393,7 @@ def random( # ========================= Cumulative Functions ========================= def cumulative_sum( - values: _ArrayOrChunkedArray | ArrayLike | Expression, + values: _ArrayOrChunkedArray | _ArrayLike | Expression, /, start: float | Scalar | None = None, *, @@ -1671,7 +1677,7 @@ def fill_null_forward( def replace_with_mask( values: _ScalarOrArray | Expression, mask: Mask, - replacements: ArrayLike, + replacements: _ArrayLike, /, *, memory_pool: MemoryPool | None = None, From ca6276d7a4d0931538753a84a80e63fca8a4526c Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Thu, 19 Nov 2026 10:30:41 +0100 Subject: [PATCH 07/33] Reorder stubs to match _compute.pyx and C++ api order (not only sections but also individual functions) --- python/pyarrow-stubs/_compute.pyi | 483 +++++++++++++++--------------- python/pyarrow-stubs/compute.pyi | 196 ++++++------ 2 files changed, 330 insertions(+), 349 deletions(-) diff --git a/python/pyarrow-stubs/_compute.pyi b/python/pyarrow-stubs/_compute.pyi index c9befae94a8f..c756b4c59dcb 100644 --- a/python/pyarrow-stubs/_compute.pyi +++ b/python/pyarrow-stubs/_compute.pyi @@ -82,7 +82,13 @@ _Tiebreaker: TypeAlias = Literal["min", "max", "first", "dense"] _TimezoneResolution: TypeAlias = Literal["raise", "earliest", "latest"] _UnexpectedKeyBehavior: TypeAlias = Literal["ignore", "raise"] +# ==================== Kernels and functions ==================== + class Kernel(_Weakrefable): ... +class ScalarKernel(Kernel): ... +class VectorKernel(Kernel): ... +class ScalarAggregateKernel(Kernel): ... +class HashAggregateKernel(Kernel): ... class Function(_Weakrefable): @property @@ -103,63 +109,49 @@ class Function(_Weakrefable): length: int | None = None, ) -> Any: ... -class FunctionOptions(_Weakrefable): - __hash__: ClassVar[None] # type: ignore[assignment] - - def serialize(self) -> Buffer: ... - @staticmethod - def deserialize(buf: Buffer) -> FunctionOptions: ... - -class FunctionRegistry(_Weakrefable): - def get_function(self, name: str) -> Function: ... - def list_functions(self) -> list[str]: ... - -class HashAggregateFunction(Function): +class ScalarFunction(Function): @property - def kernels(self) -> list[HashAggregateKernel]: ... - -class HashAggregateKernel(Kernel): ... + def kernels(self) -> list[ScalarKernel]: ... -class MetaFunction(Function): +class VectorFunction(Function): @property - def kernels(self) -> list[Kernel]: ... + def kernels(self) -> list[VectorKernel]: ... class ScalarAggregateFunction(Function): @property def kernels(self) -> list[ScalarAggregateKernel]: ... -class ScalarAggregateKernel(Kernel): ... - -class ScalarFunction(Function): +class HashAggregateFunction(Function): @property - def kernels(self) -> list[ScalarKernel]: ... - -class ScalarKernel(Kernel): ... + def kernels(self) -> list[HashAggregateKernel]: ... -class VectorFunction(Function): +class MetaFunction(Function): @property - def kernels(self) -> list[VectorKernel]: ... + def kernels(self) -> list[Kernel]: ... -class VectorKernel(Kernel): ... +class FunctionRegistry(_Weakrefable): + def get_function(self, name: str) -> Function: ... + def list_functions(self) -> list[str]: ... + +def function_registry() -> FunctionRegistry: ... +def get_function(name: str) -> Function: ... +def list_functions() -> list[str]: ... +def call_function( + name: str, + args: list[Any], + options: FunctionOptions | None = None, + memory_pool: MemoryPool | None = None, + length: int | None = None, +) -> Any: ... # ==================== Option classes ==================== -class ArraySortOptions(FunctionOptions): - def __init__( - self, - order: Order = "ascending", - *, - null_placement: NullPlacement = "at_end", - ) -> None: ... +class FunctionOptions(_Weakrefable): + __hash__: ClassVar[None] # type: ignore[assignment] -class AssumeTimezoneOptions(FunctionOptions): - def __init__( - self, - timezone: str, - *, - ambiguous: _TimezoneResolution = "raise", - nonexistent: _TimezoneResolution = "raise", - ) -> None: ... + def serialize(self) -> Buffer: ... + @staticmethod + def deserialize(buf: Buffer) -> FunctionOptions: ... class CastOptions(FunctionOptions): allow_int_overflow: bool @@ -186,27 +178,60 @@ class CastOptions(FunctionOptions): def unsafe(target_type: DataType | str | None = None) -> CastOptions: ... def is_safe(self) -> bool: ... -class CountOptions(FunctionOptions): - def __init__(self, mode: _CountMode = "only_valid") -> None: ... +class ElementWiseAggregateOptions(FunctionOptions): + def __init__(self, *, skip_nulls: bool = True) -> None: ... -class CumulativeOptions(FunctionOptions): +class RoundOptions(FunctionOptions): def __init__( - self, start: Scalar | None = None, *, skip_nulls: bool = False + self, ndigits: int = 0, round_mode: _RoundMode = "half_to_even" ) -> None: ... -class DayOfWeekOptions(FunctionOptions): +class RoundBinaryOptions(FunctionOptions): + def __init__(self, round_mode: _RoundMode = "half_to_even") -> None: ... + +class RoundTemporalOptions(FunctionOptions): def __init__( - self, *, count_from_zero: bool = True, week_start: int = 1 + self, + multiple: int = 1, + unit: _DateTimeUnit = "day", + *, + week_starts_monday: bool = True, + ceil_is_strictly_greater: bool = False, + calendar_based_origin: bool = False, ) -> None: ... -class DictionaryEncodeOptions(FunctionOptions): - def __init__(self, null_encoding: NullEncoding = "mask") -> None: ... +class RoundToMultipleOptions(FunctionOptions): + def __init__( + self, + multiple: float | Scalar = 1.0, + round_mode: _RoundMode = "half_to_even", + ) -> None: ... -class RunEndEncodeOptions(FunctionOptions): - def __init__(self, run_end_type: DataType | str = ...) -> None: ... +class JoinOptions(FunctionOptions): + def __init__( + self, + null_handling: _NullHandling = "emit_null", + null_replacement: str = "", + ) -> None: ... -class ElementWiseAggregateOptions(FunctionOptions): - def __init__(self, *, skip_nulls: bool = True) -> None: ... +class MatchSubstringOptions(FunctionOptions): + def __init__(self, pattern: str, *, ignore_case: bool = False) -> None: ... + +class PadOptions(FunctionOptions): + def __init__( + self, width: int, padding: str = " ", lean_left_on_odd_padding: bool = True + ) -> None: ... + +class ZeroFillOptions(FunctionOptions): + def __init__(self, width: int, padding: str = "0") -> None: ... + +class TrimOptions(FunctionOptions): + def __init__(self, characters: str) -> None: ... + +class ReplaceSubstringOptions(FunctionOptions): + def __init__( + self, pattern: str, replacement: str, *, max_replacements: int | None = None + ) -> None: ... class ExtractRegexOptions(FunctionOptions): def __init__(self, pattern: str) -> None: ... @@ -214,37 +239,42 @@ class ExtractRegexOptions(FunctionOptions): class ExtractRegexSpanOptions(FunctionOptions): def __init__(self, pattern: str) -> None: ... +class SliceOptions(FunctionOptions): + def __init__(self, start: int, stop: int | None = None, step: int = 1) -> None: ... + +class ListSliceOptions(FunctionOptions): + def __init__( + self, + start: int, + stop: int | None = None, + step: int = 1, + return_fixed_size_list: bool | None = None, + ) -> None: ... + +class ReplaceSliceOptions(FunctionOptions): + def __init__(self, start: int, stop: int, replacement: str) -> None: ... + class FilterOptions(FunctionOptions): def __init__( self, null_selection_behavior: NullSelectionBehavior = "drop" ) -> None: ... -class IndexOptions(FunctionOptions): - def __init__(self, value: Scalar) -> None: ... +class DictionaryEncodeOptions(FunctionOptions): + def __init__(self, null_encoding: NullEncoding = "mask") -> None: ... + +class RunEndEncodeOptions(FunctionOptions): + def __init__(self, run_end_type: DataType | str = ...) -> None: ... class InversePermutationOptions(FunctionOptions): def __init__( self, max_index: int = -1, output_type: DataType | str | None = None ) -> None: ... -class JoinOptions(FunctionOptions): - def __init__( - self, - null_handling: _NullHandling = "emit_null", - null_replacement: str = "", - ) -> None: ... - -class ListSliceOptions(FunctionOptions): - def __init__( - self, - start: int, - stop: int | None = None, - step: int = 1, - return_fixed_size_list: bool | None = None, - ) -> None: ... +class ScatterOptions(FunctionOptions): + def __init__(self, max_index: int = -1) -> None: ... -class ListFlattenOptions(FunctionOptions): - def __init__(self, recursive: bool = False) -> None: ... +class TakeOptions(FunctionOptions): + def __init__(self, *, boundscheck: bool = True) -> None: ... class MakeStructOptions(FunctionOptions): def __init__( @@ -255,127 +285,119 @@ class MakeStructOptions(FunctionOptions): field_metadata: Sequence[KeyValueMetadata | None] | None = None, ) -> None: ... +class StructFieldOptions(FunctionOptions): + def __init__( + self, + indices: Sequence[str | bytes | int] | Expression | bytes | str | int, + ) -> None: ... + +class ScalarAggregateOptions(FunctionOptions): + def __init__(self, *, skip_nulls: bool = True, min_count: int = 1) -> None: ... + +class CountOptions(FunctionOptions): + def __init__(self, mode: _CountMode = "only_valid") -> None: ... + +class IndexOptions(FunctionOptions): + def __init__(self, value: Scalar) -> None: ... + class MapLookupOptions(FunctionOptions): def __init__(self, query_key: Any, occurrence: _Occurrence) -> None: ... -class MatchSubstringOptions(FunctionOptions): - def __init__(self, pattern: str, *, ignore_case: bool = False) -> None: ... - class ModeOptions(FunctionOptions): def __init__( self, n: int = 1, *, skip_nulls: bool = True, min_count: int = 0 ) -> None: ... -class NullOptions(FunctionOptions): - def __init__(self, *, nan_is_null: bool = False) -> None: ... - -class PadOptions(FunctionOptions): +class SetLookupOptions(FunctionOptions): def __init__( - self, width: int, padding: str = " ", lean_left_on_odd_padding: bool = True + self, value_set: Array | ChunkedArray | Scalar, *, skip_nulls: bool = False ) -> None: ... -class PairwiseOptions(FunctionOptions): - def __init__(self, period: int = 1) -> None: ... - -class PartitionNthOptions(FunctionOptions): +class StrptimeOptions(FunctionOptions): def __init__( - self, pivot: int, *, null_placement: NullPlacement = "at_end" + self, format: str, unit: TimeUnit, error_is_null: bool = False ) -> None: ... -class WinsorizeOptions(FunctionOptions): - def __init__(self, lower_limit: float, upper_limit: float) -> None: ... - -class QuantileOptions(FunctionOptions): +class StrftimeOptions(FunctionOptions): def __init__( - self, - q: float | Sequence[float] = 0.5, - *, - interpolation: _Interpolation = "linear", - skip_nulls: bool = True, - min_count: int = 0, + self, format: str = "%Y-%m-%dT%H:%M:%S", locale: str = "C" ) -> None: ... -class RandomOptions(FunctionOptions): - def __init__(self, *, initializer: Hashable = "system") -> None: ... - -class RankOptions(FunctionOptions): +class DayOfWeekOptions(FunctionOptions): def __init__( - self, - sort_keys: Order | Sequence[_SortKey] = "ascending", - *, - null_placement: NullPlacement | None = None, - tiebreaker: _Tiebreaker = "first", + self, *, count_from_zero: bool = True, week_start: int = 1 ) -> None: ... -class RankQuantileOptions(FunctionOptions): +class WeekOptions(FunctionOptions): def __init__( self, - sort_keys: Order | Sequence[_SortKey] = "ascending", *, - null_placement: NullPlacement | None = None, + week_starts_monday: bool = True, + count_from_zero: bool = False, + first_week_is_fully_in_year: bool = False, ) -> None: ... -class PivotWiderOptions(FunctionOptions): +class AssumeTimezoneOptions(FunctionOptions): def __init__( self, - key_names: Sequence[str], + timezone: str, *, - unexpected_key_behavior: _UnexpectedKeyBehavior = "ignore", + ambiguous: _TimezoneResolution = "raise", + nonexistent: _TimezoneResolution = "raise", ) -> None: ... -class ReplaceSliceOptions(FunctionOptions): - def __init__(self, start: int, stop: int, replacement: str) -> None: ... +class NullOptions(FunctionOptions): + def __init__(self, *, nan_is_null: bool = False) -> None: ... -class ReplaceSubstringOptions(FunctionOptions): +class VarianceOptions(FunctionOptions): def __init__( - self, pattern: str, replacement: str, *, max_replacements: int | None = None + self, *, ddof: int = 0, skip_nulls: bool = True, min_count: int = 0 ) -> None: ... -class RoundBinaryOptions(FunctionOptions): - def __init__(self, round_mode: _RoundMode = "half_to_even") -> None: ... +class SkewOptions(FunctionOptions): + def __init__( + self, *, skip_nulls: bool = True, biased: bool = True, min_count: int = 0 + ) -> None: ... -class RoundOptions(FunctionOptions): +class SplitOptions(FunctionOptions): def __init__( - self, ndigits: int = 0, round_mode: _RoundMode = "half_to_even" + self, *, max_splits: int | None = None, reverse: bool = False ) -> None: ... -class RoundTemporalOptions(FunctionOptions): +class SplitPatternOptions(FunctionOptions): def __init__( - self, - multiple: int = 1, - unit: _DateTimeUnit = "day", - *, - week_starts_monday: bool = True, - ceil_is_strictly_greater: bool = False, - calendar_based_origin: bool = False, + self, pattern: str, *, max_splits: int | None = None, reverse: bool = False ) -> None: ... -class RoundToMultipleOptions(FunctionOptions): +class PartitionNthOptions(FunctionOptions): def __init__( - self, - multiple: float | Scalar = 1.0, - round_mode: _RoundMode = "half_to_even", + self, pivot: int, *, null_placement: NullPlacement = "at_end" ) -> None: ... -class ScalarAggregateOptions(FunctionOptions): - def __init__(self, *, skip_nulls: bool = True, min_count: int = 1) -> None: ... +class WinsorizeOptions(FunctionOptions): + def __init__(self, lower_limit: float, upper_limit: float) -> None: ... -class ScatterOptions(FunctionOptions): - def __init__(self, max_index: int = -1) -> None: ... +class CumulativeOptions(FunctionOptions): + def __init__( + self, start: Scalar | None = None, *, skip_nulls: bool = False + ) -> None: ... -class SearchSortedOptions(FunctionOptions): - def __init__(self, side: _Side = "left") -> None: ... +class PairwiseOptions(FunctionOptions): + def __init__(self, period: int = 1) -> None: ... -class SelectKOptions(FunctionOptions): - def __init__(self, k: int, sort_keys: Sequence[_SortKey]) -> None: ... +class ListFlattenOptions(FunctionOptions): + def __init__(self, recursive: bool = False) -> None: ... -class SetLookupOptions(FunctionOptions): +class ArraySortOptions(FunctionOptions): def __init__( - self, value_set: Array | ChunkedArray | Scalar, *, skip_nulls: bool = False + self, + order: Order = "ascending", + *, + null_placement: NullPlacement = "at_end", ) -> None: ... -class SliceOptions(FunctionOptions): - def __init__(self, start: int, stop: int | None = None, step: int = 1) -> None: ... +class SearchSortedOptions(FunctionOptions): + def __init__(self, side: _Side = "left") -> None: ... class SortOptions(FunctionOptions): def __init__( @@ -385,35 +407,19 @@ class SortOptions(FunctionOptions): null_placement: NullPlacement | None = None, ) -> None: ... -class SplitOptions(FunctionOptions): - def __init__( - self, *, max_splits: int | None = None, reverse: bool = False - ) -> None: ... - -class SplitPatternOptions(FunctionOptions): - def __init__( - self, pattern: str, *, max_splits: int | None = None, reverse: bool = False - ) -> None: ... - -class StrftimeOptions(FunctionOptions): - def __init__( - self, format: str = "%Y-%m-%dT%H:%M:%S", locale: str = "C" - ) -> None: ... - -class StrptimeOptions(FunctionOptions): - def __init__( - self, format: str, unit: TimeUnit, error_is_null: bool = False - ) -> None: ... +class SelectKOptions(FunctionOptions): + def __init__(self, k: int, sort_keys: Sequence[_SortKey]) -> None: ... -class StructFieldOptions(FunctionOptions): +class QuantileOptions(FunctionOptions): def __init__( self, - indices: Sequence[str | bytes | int] | Expression | bytes | str | int, + q: float | Sequence[float] = 0.5, + *, + interpolation: _Interpolation = "linear", + skip_nulls: bool = True, + min_count: int = 0, ) -> None: ... -class TakeOptions(FunctionOptions): - def __init__(self, *, boundscheck: bool = True) -> None: ... - class TDigestOptions(FunctionOptions): def __init__( self, @@ -425,98 +431,37 @@ class TDigestOptions(FunctionOptions): min_count: int = 0, ) -> None: ... -class TrimOptions(FunctionOptions): - def __init__(self, characters: str) -> None: ... - class Utf8NormalizeOptions(FunctionOptions): def __init__(self, form: _Form) -> None: ... -class VarianceOptions(FunctionOptions): +class RandomOptions(FunctionOptions): + def __init__(self, *, initializer: Hashable = "system") -> None: ... + +class RankOptions(FunctionOptions): def __init__( - self, *, ddof: int = 0, skip_nulls: bool = True, min_count: int = 0 + self, + sort_keys: Order | Sequence[_SortKey] = "ascending", + *, + null_placement: NullPlacement | None = None, + tiebreaker: _Tiebreaker = "first", ) -> None: ... -class SkewOptions(FunctionOptions): +class RankQuantileOptions(FunctionOptions): def __init__( - self, *, skip_nulls: bool = True, biased: bool = True, min_count: int = 0 + self, + sort_keys: Order | Sequence[_SortKey] = "ascending", + *, + null_placement: NullPlacement | None = None, ) -> None: ... -class WeekOptions(FunctionOptions): +class PivotWiderOptions(FunctionOptions): def __init__( self, + key_names: Sequence[str], *, - week_starts_monday: bool = True, - count_from_zero: bool = False, - first_week_is_fully_in_year: bool = False, + unexpected_key_behavior: _UnexpectedKeyBehavior = "ignore", ) -> None: ... -class ZeroFillOptions(FunctionOptions): - def __init__(self, width: int, padding: str = "0") -> None: ... - -# ==================== Functions ==================== - -def call_function( - name: str, - args: list[Any], - options: FunctionOptions | None = None, - memory_pool: MemoryPool | None = None, - length: int | None = None, -) -> Any: ... -def function_registry() -> FunctionRegistry: ... -def get_function(name: str) -> Function: ... -def list_functions() -> list[str]: ... - -# ==================== User-defined functions ==================== - -def call_tabular_function( - function_name: str, - args: Iterable[Any] | None = None, - func_registry: FunctionRegistry | None = None, -) -> RecordBatchReader: ... - -class _FunctionDoc(TypedDict): - summary: str - description: str - -def register_scalar_function( - func: Callable[..., Any], - function_name: str, - function_doc: _FunctionDoc | dict[str, str], - in_types: Mapping[str, DataType | str], - out_type: DataType | str, - func_registry: FunctionRegistry | None = None, -) -> None: ... -def register_tabular_function( - func: Callable[..., Any], - function_name: str, - function_doc: _FunctionDoc | dict[str, str], - in_types: Mapping[str, DataType | str], - out_type: DataType | str, - func_registry: FunctionRegistry | None = None, -) -> None: ... -def register_aggregate_function( - func: Callable[..., Any], - function_name: str, - function_doc: _FunctionDoc | dict[str, str], - in_types: Mapping[str, DataType | str], - out_type: DataType | str, - func_registry: FunctionRegistry | None = None, -) -> None: ... -def register_vector_function( - func: Callable[..., Any], - function_name: str, - function_doc: _FunctionDoc | dict[str, str], - in_types: Mapping[str, DataType | str], - out_type: DataType | str, - func_registry: FunctionRegistry | None = None, -) -> None: ... - -class UdfContext: - @property - def batch_length(self) -> int: ... - @property - def memory_pool(self) -> MemoryPool: ... - # ==================== Expression ==================== class _SubstraitMessage(Protocol): @@ -558,3 +503,53 @@ class Expression(_Weakrefable): ) -> Expression: ... def isin(self, values: Array | Iterable[Any]) -> Expression: ... def equals(self, other: Expression) -> bool: ... + +# ==================== User-defined functions ==================== + +class UdfContext: + @property + def batch_length(self) -> int: ... + @property + def memory_pool(self) -> MemoryPool: ... + +class _FunctionDoc(TypedDict): + summary: str + description: str + +def register_scalar_function( + func: Callable[..., Any], + function_name: str, + function_doc: _FunctionDoc | dict[str, str], + in_types: Mapping[str, DataType | str], + out_type: DataType | str, + func_registry: FunctionRegistry | None = None, +) -> None: ... +def register_vector_function( + func: Callable[..., Any], + function_name: str, + function_doc: _FunctionDoc | dict[str, str], + in_types: Mapping[str, DataType | str], + out_type: DataType | str, + func_registry: FunctionRegistry | None = None, +) -> None: ... +def register_aggregate_function( + func: Callable[..., Any], + function_name: str, + function_doc: _FunctionDoc | dict[str, str], + in_types: Mapping[str, DataType | str], + out_type: DataType | str, + func_registry: FunctionRegistry | None = None, +) -> None: ... +def register_tabular_function( + func: Callable[..., Any], + function_name: str, + function_doc: _FunctionDoc | dict[str, str], + in_types: Mapping[str, DataType | str], + out_type: DataType | str, + func_registry: FunctionRegistry | None = None, +) -> None: ... +def call_tabular_function( + function_name: str, + args: Iterable[Any] | None = None, + func_registry: FunctionRegistry | None = None, +) -> RecordBatchReader: ... diff --git a/python/pyarrow-stubs/compute.pyi b/python/pyarrow-stubs/compute.pyi index 525e0d8052c1..4acde7e401ba 100644 --- a/python/pyarrow-stubs/compute.pyi +++ b/python/pyarrow-stubs/compute.pyi @@ -297,7 +297,6 @@ _TemporalArray: TypeAlias = ( _ListArray: TypeAlias = BaseListArray | ChunkedArray # =============================== Aggregations ======================================== - def all( array: BooleanScalar | _ArrayOrChunkedArray | Expression, /, @@ -344,9 +343,6 @@ def first( options: ScalarAggregateOptions | None = None, memory_pool: MemoryPool | None = None, ) -> Scalar | Expression: ... - -last = _clone_signature(first) - def first_last( array: _ArrayOrChunkedArray | Iterable[Any] | Expression, /, @@ -364,10 +360,19 @@ def index( *, memory_pool: MemoryPool | None = None, ) -> Int64Scalar: ... +def kurtosis( + array: _NumericScalar | _ArrayOrChunkedArray | _ArrayLike | Expression, + /, + *, + skip_nulls: bool = True, + biased: bool = True, + min_count: int = 0, + options: SkewOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> DoubleScalar | Expression: ... +last = _clone_signature(first) max = _clone_signature(first) -min = _clone_signature(first) -min_max = _clone_signature(first_last) def mean( array: _NumericScalar | _ArrayOrChunkedArray | Expression, @@ -378,6 +383,10 @@ def mean( options: ScalarAggregateOptions | None = None, memory_pool: MemoryPool | None = None, ) -> Scalar | Expression: ... + +min = _clone_signature(first) +min_max = _clone_signature(first_last) + def mode( array: _NumericScalar | _ArrayOrChunkedArray | Expression, /, @@ -388,6 +397,16 @@ def mode( options: ModeOptions | None = None, memory_pool: MemoryPool | None = None, ) -> StructArray | Expression: ... +def pivot_wider( + pivot_keys: _ArrayOrChunkedArray | Sequence[str], + pivot_values: _ArrayOrChunkedArray | Sequence[Any], + /, + key_names: Sequence[str], + *, + unexpected_key_behavior: _UnexpectedKeyBehavior = "ignore", + options: PivotWiderOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> StructScalar: ... def product( array: _NumericScalar | _ArrayOrChunkedArray | Expression, /, @@ -408,6 +427,16 @@ def quantile( options: QuantileOptions | None = None, memory_pool: MemoryPool | None = None, ) -> DoubleArray | Expression: ... +def skew( + array: _NumericScalar | _ArrayOrChunkedArray | _ArrayLike | Expression, + /, + *, + skip_nulls: bool = True, + biased: bool = True, + min_count: int = 0, + options: SkewOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> DoubleScalar | Expression: ... def stddev( array: _NumericScalar | _ArrayOrChunkedArray | Expression, /, @@ -449,36 +478,6 @@ def variance( options: VarianceOptions | None = None, memory_pool: MemoryPool | None = None, ) -> DoubleScalar | Expression: ... -def skew( - array: _NumericScalar | _ArrayOrChunkedArray | _ArrayLike | Expression, - /, - *, - skip_nulls: bool = True, - biased: bool = True, - min_count: int = 0, - options: SkewOptions | None = None, - memory_pool: MemoryPool | None = None, -) -> DoubleScalar | Expression: ... -def kurtosis( - array: _NumericScalar | _ArrayOrChunkedArray | _ArrayLike | Expression, - /, - *, - skip_nulls: bool = True, - biased: bool = True, - min_count: int = 0, - options: SkewOptions | None = None, - memory_pool: MemoryPool | None = None, -) -> DoubleScalar | Expression: ... -def pivot_wider( - pivot_keys: _ArrayOrChunkedArray | Sequence[str], - pivot_values: _ArrayOrChunkedArray | Sequence[Any], - /, - key_names: Sequence[str], - *, - unexpected_key_behavior: _UnexpectedKeyBehavior = "ignore", - options: PivotWiderOptions | None = None, - memory_pool: MemoryPool | None = None, -) -> StructScalar: ... # =============================== Element-wise ("scalar") functions =================== @@ -514,6 +513,19 @@ def divide( divide_checked = _clone_signature(divide) +def exp( + exponent: _ArrayOrChunkedArray + | _FloatScalar + | _NonFloatNumericScalar + | DoubleScalar + | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _FloatArray | DoubleArray | _FloatScalar | DoubleScalar | Expression: ... + +expm1 = _clone_signature(exp) + def hypot( x: _NumericScalar | _ArrayOrChunkedArray | float | Expression, y: _NumericScalar | _ArrayOrChunkedArray | float | Expression, @@ -530,21 +542,6 @@ def modulo( ) -> _NumericScalar | _NumericArray | Expression: ... modulo_checked = _clone_signature(modulo) -remainder = _clone_signature(modulo) -remainder_checked = _clone_signature(modulo) - -def exp( - exponent: _ArrayOrChunkedArray - | _FloatScalar - | _NonFloatNumericScalar - | DoubleScalar - | Expression, - /, - *, - memory_pool: MemoryPool | None = None, -) -> _FloatArray | DoubleArray | _FloatScalar | DoubleScalar | Expression: ... - -expm1 = _clone_signature(exp) multiply = _clone_signature(add) multiply_checked = _clone_signature(add) @@ -566,6 +563,8 @@ def power( ) -> _NumericScalar | _NumericArray | Expression: ... power_checked = _clone_signature(power) +remainder = _clone_signature(modulo) +remainder_checked = _clone_signature(modulo) def sign( x: _ArrayOrChunkedArray | _NumericOrDurationScalar | Expression | float, @@ -581,12 +580,10 @@ def sqrt( ) -> _FloatArray | _FloatScalar | Expression: ... sqrt_checked = _clone_signature(sqrt) - subtract = _clone_signature(add) subtract_checked = _clone_signature(add) # ========================= Bit-wise functions ========================= - def bit_wise_and( x: _NumericScalar | _ArrayOrChunkedArray | Expression | float, y: _NumericScalar | _ArrayOrChunkedArray | Expression | float, @@ -609,7 +606,6 @@ shift_right = _clone_signature(bit_wise_and) shift_right_checked = _clone_signature(bit_wise_and) # ========================= Rounding functions ========================= - def ceil( x: _FloatScalar | _ArrayOrChunkedArray | Expression | float, /, @@ -650,7 +646,6 @@ def round_binary( trunc = _clone_signature(ceil) # ========================= Logarithmic functions ========================= - def ln( x: _NumericScalar | _ArrayOrChunkedArray | Expression | float, /, @@ -682,12 +677,6 @@ acos_checked = _clone_signature(ln) asin = _clone_signature(ln) asin_checked = _clone_signature(ln) atan = _clone_signature(ln) -cos = _clone_signature(ln) -cos_checked = _clone_signature(ln) -sin = _clone_signature(ln) -sin_checked = _clone_signature(ln) -tan = _clone_signature(ln) -tan_checked = _clone_signature(ln) def atan2( y: _NumericScalar | _ArrayOrChunkedArray | float | Expression, @@ -697,12 +686,19 @@ def atan2( memory_pool: MemoryPool | None = None, ) -> _FloatScalar | _FloatArray | Expression: ... +cos = _clone_signature(ln) +cos_checked = _clone_signature(ln) +sin = _clone_signature(ln) +sin_checked = _clone_signature(ln) +tan = _clone_signature(ln) +tan_checked = _clone_signature(ln) + # ========================= Hyperbolic trigonometric functions ========================= acosh = _clone_signature(ln) acosh_checked = _clone_signature(ln) asinh = _clone_signature(ln) -atanh_checked = _clone_signature(ln) atanh = _clone_signature(ln) +atanh_checked = _clone_signature(ln) cosh = _clone_signature(ln) sinh = _clone_signature(ln) tanh = _clone_signature(ln) @@ -732,7 +728,6 @@ def max_element_wise( min_element_wise = _clone_signature(max_element_wise) # ========================= Logical functions ========================= - def and_( x: BooleanScalar | _ArrayOrChunkedArray | bool | Expression, y: BooleanScalar | _ArrayOrChunkedArray | bool | Expression, @@ -744,9 +739,6 @@ def and_( and_kleene = _clone_signature(and_) and_not = _clone_signature(and_) and_not_kleene = _clone_signature(and_) -or_ = _clone_signature(and_) -or_kleene = _clone_signature(and_) -xor = _clone_signature(and_) def invert( x: BooleanScalar | _ArrayOrChunkedArray | Expression, @@ -755,6 +747,10 @@ def invert( memory_pool: MemoryPool | None = None, ) -> BooleanScalar | _BooleanArray | Expression: ... +or_ = _clone_signature(and_) +or_kleene = _clone_signature(and_) +xor = _clone_signature(and_) + # ========================= String predicates ========================= def ascii_is_alnum( strings: _StringScalar | _ArrayOrChunkedArray | Expression, @@ -783,7 +779,6 @@ utf8_is_title = _clone_signature(ascii_is_alnum) string_is_ascii = _clone_signature(ascii_is_alnum) # ========================= String transforms ========================= - def ascii_capitalize( strings: _StringScalar | _ArrayOrChunkedArray | Expression, /, @@ -884,7 +879,6 @@ def utf8_normalize( ) -> _StringScalar | _StringArray | Expression: ... # ========================= String padding ========================= - def ascii_center( strings: _StringScalar | _ArrayOrChunkedArray | Expression, /, @@ -915,7 +909,6 @@ def utf8_zero_fill( utf8_zfill = utf8_zero_fill # ========================= String trimming ========================= - def ascii_ltrim( strings: _StringScalar | _ArrayOrChunkedArray | Expression, /, @@ -924,13 +917,6 @@ def ascii_ltrim( options: TrimOptions | None = None, memory_pool: MemoryPool | None = None, ) -> _StringScalar | _StringArray | Expression: ... - -ascii_rtrim = _clone_signature(ascii_ltrim) -ascii_trim = _clone_signature(ascii_ltrim) -utf8_ltrim = _clone_signature(ascii_ltrim) -utf8_rtrim = _clone_signature(ascii_ltrim) -utf8_trim = _clone_signature(ascii_ltrim) - def ascii_ltrim_whitespace( strings: _StringScalar | _ArrayOrChunkedArray | Expression, /, @@ -938,14 +924,18 @@ def ascii_ltrim_whitespace( memory_pool: MemoryPool | None = None, ) -> _StringScalar | _StringArray | Expression: ... +ascii_rtrim = _clone_signature(ascii_ltrim) ascii_rtrim_whitespace = _clone_signature(ascii_ltrim_whitespace) +ascii_trim = _clone_signature(ascii_ltrim) ascii_trim_whitespace = _clone_signature(ascii_ltrim_whitespace) +utf8_ltrim = _clone_signature(ascii_ltrim) utf8_ltrim_whitespace = _clone_signature(ascii_ltrim_whitespace) +utf8_rtrim = _clone_signature(ascii_ltrim) utf8_rtrim_whitespace = _clone_signature(ascii_ltrim_whitespace) +utf8_trim = _clone_signature(ascii_ltrim) utf8_trim_whitespace = _clone_signature(ascii_ltrim_whitespace) # ========================= String splitting ========================= - def ascii_split_whitespace( strings: _StringScalar | _ArrayOrChunkedArray | Expression, /, @@ -970,7 +960,6 @@ split_pattern_regex = _clone_signature(split_pattern) utf8_split_whitespace = _clone_signature(ascii_split_whitespace) # ========================= String component extraction ========================= - def extract_regex( strings: _StringOrBinaryScalar | _ArrayOrChunkedArray | Expression, /, @@ -1062,13 +1051,6 @@ def index_in( options: SetLookupOptions | None = None, memory_pool: MemoryPool | None = None, ) -> Int32Scalar | Int32Array | ChunkedArray | Expression: ... -def index_in_meta_binary( - values: _ScalarOrArray | Expression, - value_set: _ArrayOrChunkedArray | Expression, - /, - *, - memory_pool: MemoryPool | None = None, -) -> Int32Scalar | Int32Array | ChunkedArray | Expression: ... def is_in( values: _ScalarOrArray | Expression, /, @@ -1079,14 +1061,22 @@ def is_in( memory_pool: MemoryPool | None = None, ) -> BooleanScalar | _BooleanArray | Expression: ... -is_in_meta_binary = _clone_signature(index_in_meta_binary) match_like = _clone_signature(ends_with) match_substring = _clone_signature(ends_with) match_substring_regex = _clone_signature(ends_with) starts_with = _clone_signature(ends_with) -# ========================= Categorizations ========================= +def index_in_meta_binary( + values: _ScalarOrArray | Expression, + value_set: _ArrayOrChunkedArray | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> Int32Scalar | Int32Array | ChunkedArray | Expression: ... + +is_in_meta_binary = _clone_signature(index_in_meta_binary) +# ========================= Categorizations ========================= def is_finite( values: _NumericScalar | NullScalar | _ArrayOrChunkedArray | Expression, /, @@ -1115,7 +1105,6 @@ def is_valid( true_unless_null = _clone_signature(is_valid) # ========================= Selecting / multiplexing ========================= - def case_when( cond: StructScalar | _ArrayOrChunkedArray | Expression, /, @@ -1131,9 +1120,6 @@ def choose( def coalesce( *values: _ScalarOrArray | Expression, memory_pool: MemoryPool | None = None ) -> _ScalarOrArray | Expression: ... -def fill_null( - values: _ScalarOrArray | ScalarLike, fill_value: _ArrayLike | ScalarLike -) -> _ScalarOrArray | ScalarLike: ... def if_else( cond: _ArrayLike | ScalarLike | Expression, left: _ArrayLike | ScalarLike, @@ -1142,9 +1128,11 @@ def if_else( *, memory_pool: MemoryPool | None = None, ) -> _ScalarOrArray | Expression: ... +def fill_null( + values: _ScalarOrArray | ScalarLike, fill_value: _ArrayLike | ScalarLike +) -> _ScalarOrArray | ScalarLike: ... # ========================= Structural transforms ========================= - def list_value_length( lists: _ArrayOrChunkedArray | Expression, /, @@ -1285,7 +1273,6 @@ second = _clone_signature(hour) subsecond = _clone_signature(hour) us_week = _clone_signature(iso_week) us_year = _clone_signature(iso_week) -year = _clone_signature(iso_week) def week( values: TimestampScalar | _ArrayOrChunkedArray | Expression, @@ -1297,6 +1284,9 @@ def week( options: WeekOptions | None = None, memory_pool: MemoryPool | None = None, ) -> Int64Scalar | Int64Array | ChunkedArray | Expression: ... + +year = _clone_signature(iso_week) + def year_month_day( values: _TemporalScalar | _ArrayOrChunkedArray | Expression, /, @@ -1362,7 +1352,6 @@ def weeks_between( years_between = _clone_signature(days_between) # ========================= Timezone handling ========================= - def assume_timezone( timestamps: TimestampScalar | _ArrayOrChunkedArray | Expression, /, @@ -1421,7 +1410,6 @@ def winsorize( ) -> _NumericArray | Expression: ... # ========================= Associative transforms ========================= - def dictionary_encode( array: _ScalarOrArray | Expression, /, @@ -1430,12 +1418,6 @@ def dictionary_encode( options: DictionaryEncodeOptions | None = None, memory_pool: MemoryPool | None = None, ) -> _ScalarOrArray | Expression: ... -def dictionary_decode( - dictionary_array: _ScalarOrArray | Expression, - /, - *, - memory_pool: MemoryPool | None = None, -) -> _ScalarOrArray | Expression: ... def unique( array: _ArrayOrChunkedArray | Expression, /, @@ -1448,9 +1430,14 @@ def value_counts( *, memory_pool: MemoryPool | None = None, ) -> StructArray | Expression: ... +def dictionary_decode( + dictionary_array: _ScalarOrArray | Expression, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _ScalarOrArray | Expression: ... # ========================= Selections ========================= - def array_filter( array: _ArrayOrChunkedArray | Expression, selection_filter: Mask | Expression, @@ -1511,7 +1498,6 @@ def take( ) -> _ArrayOrChunkedArray | RecordBatch | Table: ... # ========================= Containment tests ========================= - def indices_nonzero( values: _ArrayOrChunkedArray | Expression, /, @@ -1548,7 +1534,7 @@ def rank( options: RankOptions | None = None, memory_pool: MemoryPool | None = None, ) -> UInt64Array: ... -def rank_quantile( +def rank_normal( input: _ArrayOrChunkedArray, /, sort_keys: Order | Sequence[_SortKey] = "ascending", @@ -1557,7 +1543,7 @@ def rank_quantile( options: RankQuantileOptions | None = None, memory_pool: MemoryPool | None = None, ) -> DoubleArray: ... -def rank_normal( +def rank_quantile( input: _ArrayOrChunkedArray, /, sort_keys: Order | Sequence[_SortKey] = "ascending", From 9ac9de23e3ef3a005b2e6fe954baa53b796a2dfe Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Thu, 19 Nov 2026 11:02:11 +0100 Subject: [PATCH 08/33] Update count function, add and reorganize tests --- python/pyarrow-stubs-tests/test_compute.py | 60 +++++++++++++--------- python/pyarrow-stubs/compute.pyi | 2 +- 2 files changed, 38 insertions(+), 24 deletions(-) diff --git a/python/pyarrow-stubs-tests/test_compute.py b/python/pyarrow-stubs-tests/test_compute.py index 569c7517e496..96003f364b7f 100644 --- a/python/pyarrow-stubs-tests/test_compute.py +++ b/python/pyarrow-stubs-tests/test_compute.py @@ -137,7 +137,7 @@ def test_options() -> None: _: Hashable = options # type: ignore[assignment] # ty: ignore[invalid-assignment] # noqa: E501 -def test_array_functions() -> None: +def test_array_wise_functions() -> None: arr = pa.array([3, 1, 2]) table = pa.table({"a": [3, 1, 2]}) @@ -155,14 +155,8 @@ def test_array_functions() -> None: pa.UInt64Array) check(assert_type(pc.indices_nonzero(arr), pa.UInt64Array | pc.Expression), pa.UInt64Array) - check(assert_type(pc.quantile(arr, q=[0.25, 0.75]), - pa.DoubleArray | pc.Expression), - pa.DoubleArray) - check(assert_type(pc.mode(arr, n=2), pa.StructArray | pc.Expression), - pa.StructArray) check(assert_type(pc.value_counts(arr), pa.StructArray | pc.Expression), pa.StructArray) - check(assert_type(pc.random(3), pa.DoubleArray), pa.DoubleArray) mask = pa.array([True, False, True]) check(assert_type(pc.filter(table, mask), _Filtered), pa.Table) @@ -172,20 +166,31 @@ def test_array_functions() -> None: pc.Expression) # Python lists and other iterables are accepted where the stubs list them. - check(pc.round((1.5, 2.5)), pa.Array) - check(pc.first_last((1, 2)), pa.StructScalar) - check(pc.binary_repeat(pa.array(["a"]), (2,)), pa.Array) - check(pc.struct_field(pa.array([{"a": 1}]), ("a",)), pa.Array) check(assert_type(pc.partition_nth_indices([3, 1, 2], pivot=1), pa.UInt64Array | pc.Expression), pa.UInt64Array) + + taken = pc.take(arr, [0, 2]) + check(assert_type(taken, pa.Array | pa.ChunkedArray | pa.RecordBatch | pa.Table), + pa.Array) + + if TYPE_CHECKING: + pc.top_k_unstable(arr, "2") # type: ignore[arg-type] + pc.sort_indices(table, [("a", "up")]) # type: ignore[list-item] + pc.cumulative_sum(range(3)) # type: ignore[arg-type] + + +def test_element_wise_functions() -> None: + arr = pa.array([3, 1, 2]) + + check(assert_type(pc.random(3), pa.DoubleArray), pa.DoubleArray) + + # Python lists and other iterables are accepted where the stubs list them. + check(pc.round((1.5, 2.5)), pa.Array) check(pc.round([1.5, 2.5]), pa.Array) + check(pc.binary_repeat(pa.array(["a"]), (2,)), pa.Array) check(pc.binary_join_element_wise(["a", "b"], ["c", "d"], "-"), pa.Array) - - import numpy as np - check(pc.variance([1, 2, 3]), pa.DoubleScalar) - check(pc.variance((1, 2, 3)), pa.DoubleScalar) - check(pc.variance(np.array([1.0, 2.0, 3.0])), pa.DoubleScalar) + check(pc.struct_field(pa.array([{"a": 1}]), ("a",)), pa.Array) selected = pc.if_else([True, False], [1, 2], [3, 4]) check(assert_type(selected, pa.Scalar | pa.Array | pa.ChunkedArray | pc.Expression), @@ -196,11 +201,20 @@ def test_array_functions() -> None: check(pc.power(arr, 2), pa.Array) check(pc.divide(arr, 2.0), pa.Array) - taken = pc.take(arr, [0, 2]) - check(assert_type(taken, pa.Array | pa.ChunkedArray | pa.RecordBatch | pa.Table), - pa.Array) - if TYPE_CHECKING: - pc.top_k_unstable(arr, "2") # type: ignore[arg-type] - pc.sort_indices(table, [("a", "up")]) # type: ignore[list-item] - pc.cumulative_sum(range(3)) # type: ignore[arg-type] +def test_agg_functions() -> None: + import numpy as np + + arr = pa.array([3, 1, 2]) + scalar = pa.scalar([1, 2]) + + check(pc.count(scalar), pa.Int64Scalar) + check(pc.first_last((1, 2)), pa.StructScalar) + check(assert_type(pc.quantile(arr, q=[0.25, 0.75]), + pa.DoubleArray | pc.Expression), + pa.DoubleArray) + check(assert_type(pc.mode(arr, n=2), pa.StructArray | pc.Expression), + pa.StructArray) + check(pc.variance([1, 2, 3]), pa.DoubleScalar) + check(pc.variance((1, 2, 3)), pa.DoubleScalar) + check(pc.variance(np.array([1.0, 2.0, 3.0])), pa.DoubleScalar) diff --git a/python/pyarrow-stubs/compute.pyi b/python/pyarrow-stubs/compute.pyi index 4acde7e401ba..d82519a7ed7e 100644 --- a/python/pyarrow-stubs/compute.pyi +++ b/python/pyarrow-stubs/compute.pyi @@ -319,7 +319,7 @@ def approximate_median( memory_pool: MemoryPool | None = None, ) -> DoubleScalar | Expression: ... def count( - array: _ArrayOrChunkedArray | Expression, + array: Scalar | _ArrayOrChunkedArray | Expression, /, mode: _CountMode = "only_valid", *, From 396866bdcd65a2d669591177e1647f1afe87cf6f Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Thu, 19 Nov 2026 17:00:04 +0100 Subject: [PATCH 09/33] Use general Scalar in parameters, no narrow types --- python/pyarrow-stubs-tests/test_compute.py | 6 +- python/pyarrow-stubs/compute.pyi | 223 ++++++++++----------- 2 files changed, 106 insertions(+), 123 deletions(-) diff --git a/python/pyarrow-stubs-tests/test_compute.py b/python/pyarrow-stubs-tests/test_compute.py index 96003f364b7f..9d1f6ea7de87 100644 --- a/python/pyarrow-stubs-tests/test_compute.py +++ b/python/pyarrow-stubs-tests/test_compute.py @@ -206,10 +206,14 @@ def test_agg_functions() -> None: import numpy as np arr = pa.array([3, 1, 2]) - scalar = pa.scalar([1, 2]) + scalar = pa.scalar(1) check(pc.count(scalar), pa.Int64Scalar) + check(pc.count_distinct(scalar), pa.Int64Scalar) + check(pc.first(scalar), pa.Int64Scalar) + check(pc.last(scalar), pa.Int64Scalar) check(pc.first_last((1, 2)), pa.StructScalar) + check(pc.first_last(scalar), pa.StructScalar) check(assert_type(pc.quantile(arr, q=[0.25, 0.75]), pa.DoubleArray | pc.Expression), pa.DoubleArray) diff --git a/python/pyarrow-stubs/compute.pyi b/python/pyarrow-stubs/compute.pyi index d82519a7ed7e..00b55f6e1779 100644 --- a/python/pyarrow-stubs/compute.pyi +++ b/python/pyarrow-stubs/compute.pyi @@ -49,7 +49,6 @@ from pyarrow.__lib.scalar import ( ListScalar, ListViewScalar, MonthDayNanoIntervalScalar, - NullScalar, Scalar, StringScalar, StringViewScalar, @@ -227,7 +226,6 @@ _FloatScalar: TypeAlias = HalfFloatScalar | FloatScalar | DoubleScalar _DecimalScalar: TypeAlias = ( Decimal32Scalar | Decimal64Scalar | Decimal128Scalar | Decimal256Scalar ) -_NonFloatNumericScalar: TypeAlias = _IntegerScalar | _DecimalScalar _NumericScalar: TypeAlias = _IntegerScalar | _FloatScalar | _DecimalScalar _BinaryScalar: TypeAlias = ( BinaryScalar | LargeBinaryScalar | BinaryViewScalar | FixedSizeBinaryScalar @@ -298,7 +296,7 @@ _ListArray: TypeAlias = BaseListArray | ChunkedArray # =============================== Aggregations ======================================== def all( - array: BooleanScalar | _ArrayOrChunkedArray | Expression, + array: _ScalarOrArray | Expression, /, *, skip_nulls: bool = True, @@ -310,7 +308,7 @@ def all( any = _clone_signature(all) def approximate_median( - array: _NumericScalar | _ArrayOrChunkedArray | Expression, + array: _ScalarOrArray | Expression, /, *, skip_nulls: bool = True, @@ -319,7 +317,7 @@ def approximate_median( memory_pool: MemoryPool | None = None, ) -> DoubleScalar | Expression: ... def count( - array: Scalar | _ArrayOrChunkedArray | Expression, + array: _ScalarOrArray | Expression, /, mode: _CountMode = "only_valid", *, @@ -327,7 +325,7 @@ def count( memory_pool: MemoryPool | None = None, ) -> Int64Scalar | Expression: ... def count_distinct( - array: _ArrayOrChunkedArray | Expression, + array: _ScalarOrArray | Expression, /, mode: _CountMode = "only_valid", *, @@ -335,7 +333,7 @@ def count_distinct( memory_pool: MemoryPool | None = None, ) -> Int64Scalar | Expression: ... def first( - array: _ArrayOrChunkedArray | Expression, + array: _ScalarOrArray | Expression, /, *, skip_nulls: bool = True, @@ -344,7 +342,7 @@ def first( memory_pool: MemoryPool | None = None, ) -> Scalar | Expression: ... def first_last( - array: _ArrayOrChunkedArray | Iterable[Any] | Expression, + array: _ScalarOrArray | Iterable[Any] | Expression, /, *, skip_nulls: bool = True, @@ -361,7 +359,7 @@ def index( memory_pool: MemoryPool | None = None, ) -> Int64Scalar: ... def kurtosis( - array: _NumericScalar | _ArrayOrChunkedArray | _ArrayLike | Expression, + array: _ScalarOrArray | _ArrayLike | Expression, /, *, skip_nulls: bool = True, @@ -375,7 +373,7 @@ last = _clone_signature(first) max = _clone_signature(first) def mean( - array: _NumericScalar | _ArrayOrChunkedArray | Expression, + array: _ScalarOrArray | Expression, /, *, skip_nulls: bool = True, @@ -388,7 +386,7 @@ min = _clone_signature(first) min_max = _clone_signature(first_last) def mode( - array: _NumericScalar | _ArrayOrChunkedArray | Expression, + array: _ScalarOrArray | Expression, /, n: int = 1, *, @@ -408,7 +406,7 @@ def pivot_wider( memory_pool: MemoryPool | None = None, ) -> StructScalar: ... def product( - array: _NumericScalar | _ArrayOrChunkedArray | Expression, + array: _ScalarOrArray | Expression, /, *, skip_nulls: bool = True, @@ -417,7 +415,7 @@ def product( memory_pool: MemoryPool | None = None, ) -> _NumericScalar | Expression: ... def quantile( - array: _NumericScalar | _ArrayOrChunkedArray | Expression, + array: _ScalarOrArray | Expression, /, q: float | Sequence[float] = 0.5, *, @@ -428,7 +426,7 @@ def quantile( memory_pool: MemoryPool | None = None, ) -> DoubleArray | Expression: ... def skew( - array: _NumericScalar | _ArrayOrChunkedArray | _ArrayLike | Expression, + array: _ScalarOrArray | _ArrayLike | Expression, /, *, skip_nulls: bool = True, @@ -438,7 +436,7 @@ def skew( memory_pool: MemoryPool | None = None, ) -> DoubleScalar | Expression: ... def stddev( - array: _NumericScalar | _ArrayOrChunkedArray | Expression, + array: _ScalarOrArray | Expression, /, *, ddof: float = 0, @@ -448,7 +446,7 @@ def stddev( memory_pool: MemoryPool | None = None, ) -> DoubleScalar | Expression: ... def sum( - array: _NumericScalar | _ArrayOrChunkedArray | Expression, + array: _ScalarOrArray | Expression, /, *, skip_nulls: bool = True, @@ -457,7 +455,7 @@ def sum( memory_pool: MemoryPool | None = None, ) -> _NumericScalar | Expression: ... def tdigest( - array: _NumericScalar | _ArrayOrChunkedArray | Expression, + array: _ScalarOrArray | Expression, /, q: float | Sequence[float] = 0.5, *, @@ -469,7 +467,7 @@ def tdigest( memory_pool: MemoryPool | None = None, ) -> DoubleArray | Expression: ... def variance( - array: _NumericScalar | _ArrayOrChunkedArray | _ArrayLike | Expression, + array: _ScalarOrArray | _ArrayLike | Expression, /, *, ddof: int = 0, @@ -483,7 +481,7 @@ def variance( # ========================= Arithmetic functions ========================= def abs( - x: _NumericOrDurationScalar | _ArrayOrChunkedArray | Expression | float, + x: _ScalarOrArray | Expression | float, /, *, memory_pool: MemoryPool | None = None, @@ -492,10 +490,8 @@ def abs( abs_checked = _clone_signature(abs) def add( - x: _NumericOrTemporalScalar | _ArrayOrChunkedArray | _ArrayLike | int | Expression, - y: ( - _NumericOrTemporalScalar | _ArrayOrChunkedArray | _ArrayLike | int | Expression - ), + x: _ScalarOrArray | _ArrayLike | int | Expression, + y: _ScalarOrArray | _ArrayLike | int | Expression, /, *, memory_pool: MemoryPool | None = None, @@ -504,8 +500,8 @@ def add( add_checked = _clone_signature(add) def divide( - x: _NumericOrTemporalScalar | _ArrayOrChunkedArray | Expression | float, - y: _NumericOrTemporalScalar | _ArrayOrChunkedArray | Expression | float, + x: _ScalarOrArray | Expression | float, + y: _ScalarOrArray | Expression | float, /, *, memory_pool: MemoryPool | None = None, @@ -514,11 +510,7 @@ def divide( divide_checked = _clone_signature(divide) def exp( - exponent: _ArrayOrChunkedArray - | _FloatScalar - | _NonFloatNumericScalar - | DoubleScalar - | Expression, + exponent: _ScalarOrArray | Expression, /, *, memory_pool: MemoryPool | None = None, @@ -527,15 +519,15 @@ def exp( expm1 = _clone_signature(exp) def hypot( - x: _NumericScalar | _ArrayOrChunkedArray | float | Expression, - y: _NumericScalar | _ArrayOrChunkedArray | float | Expression, + x: _ScalarOrArray | float | Expression, + y: _ScalarOrArray | float | Expression, /, *, memory_pool: MemoryPool | None = None, ) -> _FloatScalar | _FloatArray | Expression: ... def modulo( - dividend: _NumericScalar | _ArrayOrChunkedArray | float | Expression, - divisor: _NumericScalar | _ArrayOrChunkedArray | float | Expression, + dividend: _ScalarOrArray | float | Expression, + divisor: _ScalarOrArray | float | Expression, /, *, memory_pool: MemoryPool | None = None, @@ -546,7 +538,7 @@ multiply = _clone_signature(add) multiply_checked = _clone_signature(add) def negate( - x: _NumericOrDurationScalar | _ArrayOrChunkedArray | Expression | float, + x: _ScalarOrArray | Expression | float, /, *, memory_pool: MemoryPool | None = None, @@ -555,8 +547,8 @@ def negate( negate_checked = _clone_signature(negate) def power( - base: _NumericScalar | Expression | _ArrayOrChunkedArray | float, - exponent: _NumericScalar | Expression | _ArrayOrChunkedArray | float, + base: _ScalarOrArray | Expression | float, + exponent: _ScalarOrArray | Expression | float, /, *, memory_pool: MemoryPool | None = None, @@ -567,13 +559,13 @@ remainder = _clone_signature(modulo) remainder_checked = _clone_signature(modulo) def sign( - x: _ArrayOrChunkedArray | _NumericOrDurationScalar | Expression | float, + x: _ScalarOrArray | Expression | float, /, *, memory_pool: MemoryPool | None = None, ) -> Int8Scalar | _FloatScalar | NumericArray | ChunkedArray | Expression: ... def sqrt( - x: _ArrayOrChunkedArray | _NumericScalar | Expression | float, + x: _ScalarOrArray | Expression | float, /, *, memory_pool: MemoryPool | None = None, @@ -585,14 +577,14 @@ subtract_checked = _clone_signature(add) # ========================= Bit-wise functions ========================= def bit_wise_and( - x: _NumericScalar | _ArrayOrChunkedArray | Expression | float, - y: _NumericScalar | _ArrayOrChunkedArray | Expression | float, + x: _ScalarOrArray | Expression | float, + y: _ScalarOrArray | Expression | float, /, *, memory_pool: MemoryPool | None = None, ) -> _NumericScalar | _NumericArray | Expression: ... def bit_wise_not( - x: _NumericScalar | _ArrayOrChunkedArray | Expression | float, + x: _ScalarOrArray | Expression | float, /, *, memory_pool: MemoryPool | None = None, @@ -607,7 +599,7 @@ shift_right_checked = _clone_signature(bit_wise_and) # ========================= Rounding functions ========================= def ceil( - x: _FloatScalar | _ArrayOrChunkedArray | Expression | float, + x: _ScalarOrArray | Expression | float, /, *, memory_pool: MemoryPool | None = None, @@ -616,7 +608,7 @@ def ceil( floor = _clone_signature(ceil) def round( - x: _NumericScalar | _ArrayOrChunkedArray | Iterable[Any] | Expression | float, + x: _ScalarOrArray | Iterable[Any] | Expression | float, /, ndigits: int = 0, round_mode: _RoundMode = "half_to_even", @@ -625,17 +617,17 @@ def round( memory_pool: MemoryPool | None = None, ) -> _NumericScalar | _NumericArray | Expression: ... def round_to_multiple( - x: _NumericScalar | _ArrayOrChunkedArray | Iterable[Any] | Expression | float, + x: _ScalarOrArray | Iterable[Any] | Expression | float, /, - multiple: float | _NumericScalar = 1.0, + multiple: float | Scalar = 1.0, round_mode: _RoundMode = "half_to_even", *, options: RoundToMultipleOptions | None = None, memory_pool: MemoryPool | None = None, ) -> _NumericScalar | _NumericArray | Expression: ... def round_binary( - x: _NumericScalar | _ArrayOrChunkedArray | Iterable[Any] | float | Expression, - s: _SignedIntegerScalar | _ArrayOrChunkedArray | int | Expression, + x: _ScalarOrArray | Iterable[Any] | float | Expression, + s: _ScalarOrArray | int | Expression, /, round_mode: _RoundMode = "half_to_even", *, @@ -647,7 +639,7 @@ trunc = _clone_signature(ceil) # ========================= Logarithmic functions ========================= def ln( - x: _NumericScalar | _ArrayOrChunkedArray | Expression | float, + x: _ScalarOrArray | Expression | float, /, *, memory_pool: MemoryPool | None = None, @@ -662,8 +654,8 @@ log2 = _clone_signature(ln) log2_checked = _clone_signature(ln) def logb( - x: _NumericScalar | _ArrayOrChunkedArray | float | Expression, - b: _NumericScalar | _ArrayOrChunkedArray | float | Expression, + x: _ScalarOrArray | float | Expression, + b: _ScalarOrArray | float | Expression, /, *, memory_pool: MemoryPool | None = None, @@ -679,8 +671,8 @@ asin_checked = _clone_signature(ln) atan = _clone_signature(ln) def atan2( - y: _NumericScalar | _ArrayOrChunkedArray | float | Expression, - x: _NumericScalar | _ArrayOrChunkedArray | float | Expression, + y: _ScalarOrArray | float | Expression, + x: _ScalarOrArray | float | Expression, /, *, memory_pool: MemoryPool | None = None, @@ -729,8 +721,8 @@ min_element_wise = _clone_signature(max_element_wise) # ========================= Logical functions ========================= def and_( - x: BooleanScalar | _ArrayOrChunkedArray | bool | Expression, - y: BooleanScalar | _ArrayOrChunkedArray | bool | Expression, + x: _ScalarOrArray | bool | Expression, + y: _ScalarOrArray | bool | Expression, /, *, memory_pool: MemoryPool | None = None, @@ -741,7 +733,7 @@ and_not = _clone_signature(and_) and_not_kleene = _clone_signature(and_) def invert( - x: BooleanScalar | _ArrayOrChunkedArray | Expression, + x: _ScalarOrArray | Expression, /, *, memory_pool: MemoryPool | None = None, @@ -753,7 +745,7 @@ xor = _clone_signature(and_) # ========================= String predicates ========================= def ascii_is_alnum( - strings: _StringScalar | _ArrayOrChunkedArray | Expression, + strings: _ScalarOrArray | Expression, /, *, memory_pool: MemoryPool | None = None, @@ -780,7 +772,7 @@ string_is_ascii = _clone_signature(ascii_is_alnum) # ========================= String transforms ========================= def ascii_capitalize( - strings: _StringScalar | _ArrayOrChunkedArray | Expression, + strings: _ScalarOrArray | Expression, /, *, memory_pool: MemoryPool | None = None, @@ -793,7 +785,7 @@ ascii_title = _clone_signature(ascii_capitalize) ascii_upper = _clone_signature(ascii_capitalize) def binary_length( - strings: _StringOrBinaryScalar | _ArrayOrChunkedArray | Expression, + strings: _ScalarOrArray | Expression, /, *, memory_pool: MemoryPool | None = None, @@ -801,14 +793,14 @@ def binary_length( Int32Scalar | Int64Scalar | Int32Array | Int64Array | ChunkedArray | Expression ): ... def binary_repeat( - strings: _StringOrBinaryScalar | _ArrayOrChunkedArray | Expression, + strings: _ScalarOrArray | Expression, num_repeats: int | _ArrayOrChunkedArray | Iterable[int | None] | Expression, /, *, memory_pool: MemoryPool | None = None, ) -> _StringOrBinaryScalar | _StringOrBinaryArray | Expression: ... def binary_replace_slice( - strings: _StringOrBinaryScalar | _ArrayOrChunkedArray | Expression, + strings: _ScalarOrArray | Expression, /, start: int, stop: int, @@ -818,13 +810,13 @@ def binary_replace_slice( memory_pool: MemoryPool | None = None, ) -> _StringOrBinaryScalar | _StringOrBinaryArray | Expression: ... def binary_reverse( - strings: _BinaryScalar | _ArrayOrChunkedArray | Expression, + strings: _ScalarOrArray | Expression, /, *, memory_pool: MemoryPool | None = None, ) -> _BinaryScalar | _BinaryArray | Expression: ... def replace_substring( - strings: _StringScalar | _ArrayOrChunkedArray | Expression, + strings: _ScalarOrArray | Expression, /, pattern: str | bytes, replacement: str | bytes, @@ -837,13 +829,13 @@ def replace_substring( replace_substring_regex = _clone_signature(replace_substring) def utf8_capitalize( - strings: _StringScalar | _ArrayOrChunkedArray | Expression, + strings: _ScalarOrArray | Expression, /, *, memory_pool: MemoryPool | None = None, ) -> _StringScalar | _StringArray | Expression: ... def utf8_length( - strings: _StringScalar | _ArrayOrChunkedArray | Expression, + strings: _ScalarOrArray | Expression, /, *, memory_pool: MemoryPool | None = None, @@ -854,7 +846,7 @@ def utf8_length( utf8_lower = _clone_signature(utf8_capitalize) def utf8_replace_slice( - strings: _StringScalar | _ArrayOrChunkedArray | Expression, + strings: _ScalarOrArray | Expression, /, start: int, stop: int, @@ -870,7 +862,7 @@ utf8_title = _clone_signature(utf8_capitalize) utf8_upper = _clone_signature(utf8_capitalize) def utf8_normalize( - strings: _StringScalar | _ArrayOrChunkedArray | Expression, + strings: _ScalarOrArray | Expression, /, form: _Form, *, @@ -880,7 +872,7 @@ def utf8_normalize( # ========================= String padding ========================= def ascii_center( - strings: _StringScalar | _ArrayOrChunkedArray | Expression, + strings: _ScalarOrArray | Expression, /, width: int, padding: str = " ", @@ -897,7 +889,7 @@ utf8_lpad = _clone_signature(ascii_center) utf8_rpad = _clone_signature(ascii_center) def utf8_zero_fill( - strings: _StringScalar | _ArrayOrChunkedArray | Expression, + strings: _ScalarOrArray | Expression, /, width: int, padding: str = "0", @@ -910,7 +902,7 @@ utf8_zfill = utf8_zero_fill # ========================= String trimming ========================= def ascii_ltrim( - strings: _StringScalar | _ArrayOrChunkedArray | Expression, + strings: _ScalarOrArray | Expression, /, characters: str, *, @@ -918,7 +910,7 @@ def ascii_ltrim( memory_pool: MemoryPool | None = None, ) -> _StringScalar | _StringArray | Expression: ... def ascii_ltrim_whitespace( - strings: _StringScalar | _ArrayOrChunkedArray | Expression, + strings: _ScalarOrArray | Expression, /, *, memory_pool: MemoryPool | None = None, @@ -937,7 +929,7 @@ utf8_trim_whitespace = _clone_signature(ascii_ltrim_whitespace) # ========================= String splitting ========================= def ascii_split_whitespace( - strings: _StringScalar | _ArrayOrChunkedArray | Expression, + strings: _ScalarOrArray | Expression, /, *, max_splits: int | None = None, @@ -946,7 +938,7 @@ def ascii_split_whitespace( memory_pool: MemoryPool | None = None, ) -> _ListScalar | _ListArray | Expression: ... def split_pattern( - strings: _StringOrBinaryScalar | _ArrayOrChunkedArray | Expression, + strings: _ScalarOrArray | Expression, /, pattern: str, *, @@ -961,7 +953,7 @@ utf8_split_whitespace = _clone_signature(ascii_split_whitespace) # ========================= String component extraction ========================= def extract_regex( - strings: _StringOrBinaryScalar | _ArrayOrChunkedArray | Expression, + strings: _ScalarOrArray | Expression, /, pattern: str, *, @@ -973,19 +965,14 @@ extract_regex_span = _clone_signature(extract_regex) # ========================= String joining ========================= def binary_join( - strings: _ListScalar | _ArrayOrChunkedArray | Expression, - separator: str | bytes | _StringOrBinaryScalar | _ArrayOrChunkedArray | Expression, + strings: _ScalarOrArray | Expression, + separator: str | bytes | _ScalarOrArray | Expression, /, *, memory_pool: MemoryPool | None = None, ) -> _StringOrBinaryScalar | _StringOrBinaryArray | Expression: ... def binary_join_element_wise( - *strings: str - | bytes - | _StringOrBinaryScalar - | _ArrayOrChunkedArray - | Iterable[Any] - | Expression, + *strings: str | bytes | _ScalarOrArray | Iterable[Any] | Expression, null_handling: _NullHandling = "emit_null", null_replacement: str = "", options: JoinOptions | None = None, @@ -994,7 +981,7 @@ def binary_join_element_wise( # ========================= String Slicing ========================= def binary_slice( - strings: _BinaryScalar | _ArrayOrChunkedArray | Expression, + strings: _ScalarOrArray | Expression, /, start: int, stop: int | None = None, @@ -1004,7 +991,7 @@ def binary_slice( memory_pool: MemoryPool | None = None, ) -> _BinaryScalar | _BinaryArray | Expression: ... def utf8_slice_codeunits( - strings: _StringScalar | _ArrayOrChunkedArray | Expression, + strings: _ScalarOrArray | Expression, /, start: int, stop: int | None = None, @@ -1016,7 +1003,7 @@ def utf8_slice_codeunits( # ========================= Containment tests ========================= def count_substring( - strings: _StringOrBinaryScalar | _ArrayOrChunkedArray | Expression, + strings: _ScalarOrArray | Expression, /, pattern: str, *, @@ -1030,7 +1017,7 @@ def count_substring( count_substring_regex = _clone_signature(count_substring) def ends_with( - strings: _StringOrBinaryScalar | _ArrayOrChunkedArray | Expression, + strings: _ScalarOrArray | Expression, /, pattern: str, *, @@ -1078,7 +1065,7 @@ is_in_meta_binary = _clone_signature(index_in_meta_binary) # ========================= Categorizations ========================= def is_finite( - values: _NumericScalar | NullScalar | _ArrayOrChunkedArray | Expression, + values: _ScalarOrArray | Expression, /, *, memory_pool: MemoryPool | None = None, @@ -1106,7 +1093,7 @@ true_unless_null = _clone_signature(is_valid) # ========================= Selecting / multiplexing ========================= def case_when( - cond: StructScalar | _ArrayOrChunkedArray | Expression, + cond: _ScalarOrArray | Expression, /, *cases: _ScalarOrArray | _ArrayLike, memory_pool: MemoryPool | None = None, @@ -1152,7 +1139,7 @@ def make_struct( # ========================= Conversions ========================= def ceil_temporal( - timestamps: _TemporalScalar | _ArrayOrChunkedArray | Expression, + timestamps: _ScalarOrArray | Expression, /, multiple: int = 1, unit: _DateTimeUnit = "day", @@ -1175,7 +1162,7 @@ def cast( memory_pool: MemoryPool | None = None, ) -> Scalar | Array | ChunkedArray | Table: ... def strftime( - timestamps: _TemporalScalar | _ArrayOrChunkedArray | Expression, + timestamps: _ScalarOrArray | Expression, /, format: str = "%Y-%m-%dT%H:%M:%S", locale: str = "C", @@ -1184,7 +1171,7 @@ def strftime( memory_pool: MemoryPool | None = None, ) -> StringScalar | StringArray | ChunkedArray | Expression: ... def strptime( - strings: _StringScalar | _ArrayOrChunkedArray | Expression, + strings: _ScalarOrArray | Expression, /, format: str, unit: TimeUnit, @@ -1210,13 +1197,13 @@ def run_end_decode( # ========================= Temporal component extraction ========================= def day( - values: _TemporalScalar | _ArrayOrChunkedArray | Expression, + values: _ScalarOrArray | Expression, /, *, memory_pool: MemoryPool | None = None, ) -> Int64Scalar | Int64Array | ChunkedArray | Expression: ... def day_of_week( - values: _TemporalScalar | _ArrayOrChunkedArray | Expression, + values: _ScalarOrArray | Expression, /, *, count_from_zero: bool = True, @@ -1228,23 +1215,19 @@ def day_of_week( day_of_year = _clone_signature(day) def hour( - values: TimestampScalar - | Time32Scalar - | Time64Scalar - | _ArrayOrChunkedArray - | Expression, + values: _ScalarOrArray | Expression, /, *, memory_pool: MemoryPool | None = None, ) -> Int64Scalar | Int64Array | ChunkedArray | Expression: ... def is_dst( - values: TimestampScalar | _ArrayOrChunkedArray | Expression, + values: _ScalarOrArray | Expression, /, *, memory_pool: MemoryPool | None = None, ) -> BooleanScalar | _BooleanArray | Expression: ... def iso_week( - values: TimestampScalar | _ArrayOrChunkedArray | Expression, + values: _ScalarOrArray | Expression, /, *, memory_pool: MemoryPool | None = None, @@ -1253,11 +1236,7 @@ def iso_week( iso_year = _clone_signature(iso_week) def is_leap_year( - values: TimestampScalar - | Date32Scalar - | Date64Scalar - | _ArrayOrChunkedArray - | Expression, + values: _ScalarOrArray | Expression, /, *, memory_pool: MemoryPool | None = None, @@ -1275,7 +1254,7 @@ us_week = _clone_signature(iso_week) us_year = _clone_signature(iso_week) def week( - values: TimestampScalar | _ArrayOrChunkedArray | Expression, + values: _ScalarOrArray | Expression, /, *, week_starts_monday: bool = True, @@ -1288,7 +1267,7 @@ def week( year = _clone_signature(iso_week) def year_month_day( - values: _TemporalScalar | _ArrayOrChunkedArray | Expression, + values: _ScalarOrArray | Expression, /, *, memory_pool: MemoryPool | None = None, @@ -1298,15 +1277,15 @@ iso_calendar = _clone_signature(year_month_day) # ========================= Temporal difference ========================= def day_time_interval_between( - start: _TemporalScalar | _ArrayOrChunkedArray | Expression, - end: _TemporalScalar | _ArrayOrChunkedArray | Expression, + start: _ScalarOrArray | Expression, + end: _ScalarOrArray | Expression, /, *, memory_pool: MemoryPool | None = None, ) -> _ScalarOrArray | Expression: ... def days_between( - start: _TemporalScalar | _ArrayOrChunkedArray | Expression, - end: _TemporalScalar | _ArrayOrChunkedArray | Expression, + start: _ScalarOrArray | Expression, + end: _ScalarOrArray | Expression, /, *, memory_pool: MemoryPool | None = None, @@ -1318,8 +1297,8 @@ milliseconds_between = _clone_signature(days_between) minutes_between = _clone_signature(days_between) def month_day_nano_interval_between( - start: _TemporalScalar | _ArrayOrChunkedArray | Expression, - end: _TemporalScalar | _ArrayOrChunkedArray | Expression, + start: _ScalarOrArray | Expression, + end: _ScalarOrArray | Expression, /, *, memory_pool: MemoryPool | None = None, @@ -1327,8 +1306,8 @@ def month_day_nano_interval_between( MonthDayNanoIntervalScalar | MonthDayNanoIntervalArray | ChunkedArray | Expression ): ... def month_interval_between( - start: _TemporalScalar | _ArrayOrChunkedArray | Expression, - end: _TemporalScalar | _ArrayOrChunkedArray | Expression, + start: _ScalarOrArray | Expression, + end: _ScalarOrArray | Expression, /, *, memory_pool: MemoryPool | None = None, @@ -1339,8 +1318,8 @@ quarters_between = _clone_signature(days_between) seconds_between = _clone_signature(days_between) def weeks_between( - start: _TemporalScalar | _ArrayOrChunkedArray | Expression, - end: _TemporalScalar | _ArrayOrChunkedArray | Expression, + start: _ScalarOrArray | Expression, + end: _ScalarOrArray | Expression, /, *, count_from_zero: bool = True, @@ -1353,7 +1332,7 @@ years_between = _clone_signature(days_between) # ========================= Timezone handling ========================= def assume_timezone( - timestamps: TimestampScalar | _ArrayOrChunkedArray | Expression, + timestamps: _ScalarOrArray | Expression, /, timezone: str, *, @@ -1363,7 +1342,7 @@ def assume_timezone( memory_pool: MemoryPool | None = None, ) -> TimestampScalar | TimestampArray | ChunkedArray | Expression: ... def local_timestamp( - values: TimestampScalar | _ArrayOrChunkedArray | Expression, + values: _ScalarOrArray | Expression, /, *, memory_pool: MemoryPool | None = None, @@ -1598,8 +1577,8 @@ def bottom_k_unstable( # ========================= Structural transforms ========================= def list_element( - lists: _ListScalar | _ArrayOrChunkedArray | Expression, - index: int | _IntegerScalar | Expression, + lists: _ScalarOrArray | Expression, + index: int | Scalar | Expression, /, *, memory_pool: MemoryPool | None = None, @@ -1639,7 +1618,7 @@ def map_lookup( memory_pool: MemoryPool | None = None, ) -> _ScalarOrArray | Expression: ... def struct_field( - values: StructScalar | _ArrayOrChunkedArray | Expression, + values: _ScalarOrArray | Expression, /, indices: Sequence[str | bytes | int] | Expression | bytes | str | int, *, From 7f5259c022f7f42b865921b48fb4f0cb556f735e Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Fri, 20 Nov 2026 06:37:53 +0100 Subject: [PATCH 10/33] Review the rest of the aggregations section in compute.pyi --- python/pyarrow-stubs-tests/test_compute.py | 17 ++++++++++++++--- python/pyarrow-stubs/compute.pyi | 4 ++-- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/python/pyarrow-stubs-tests/test_compute.py b/python/pyarrow-stubs-tests/test_compute.py index 9d1f6ea7de87..7a7921f55407 100644 --- a/python/pyarrow-stubs-tests/test_compute.py +++ b/python/pyarrow-stubs-tests/test_compute.py @@ -29,6 +29,15 @@ pa.Array | pa.ChunkedArray | pa.RecordBatch | pa.Table | pc.Expression ) +_Quantile: TypeAlias = ( + pa.NumericArray + | pa.Decimal32Array + | pa.Decimal64Array + | pa.Decimal128Array + | pa.Decimal256Array + | pc.Expression +) + def test_expression() -> None: field = pc.field("a") @@ -214,11 +223,13 @@ def test_agg_functions() -> None: check(pc.last(scalar), pa.Int64Scalar) check(pc.first_last((1, 2)), pa.StructScalar) check(pc.first_last(scalar), pa.StructScalar) - check(assert_type(pc.quantile(arr, q=[0.25, 0.75]), - pa.DoubleArray | pc.Expression), - pa.DoubleArray) + check(assert_type(pc.quantile(arr, q=[0.25, 0.75]), _Quantile), pa.DoubleArray) + check(assert_type(pc.quantile(arr, interpolation="lower"), _Quantile), + pa.Int64Array) check(assert_type(pc.mode(arr, n=2), pa.StructArray | pc.Expression), pa.StructArray) check(pc.variance([1, 2, 3]), pa.DoubleScalar) check(pc.variance((1, 2, 3)), pa.DoubleScalar) check(pc.variance(np.array([1.0, 2.0, 3.0])), pa.DoubleScalar) + check(pc.mean(arr), pa.DoubleScalar) + check(pc.mean(pc.field(0)), pc.Expression) diff --git a/python/pyarrow-stubs/compute.pyi b/python/pyarrow-stubs/compute.pyi index 00b55f6e1779..2571a655e040 100644 --- a/python/pyarrow-stubs/compute.pyi +++ b/python/pyarrow-stubs/compute.pyi @@ -380,7 +380,7 @@ def mean( min_count: int = 1, options: ScalarAggregateOptions | None = None, memory_pool: MemoryPool | None = None, -) -> Scalar | Expression: ... +) -> DoubleScalar | _DecimalScalar | Expression: ... min = _clone_signature(first) min_max = _clone_signature(first_last) @@ -424,7 +424,7 @@ def quantile( min_count: int = 0, options: QuantileOptions | None = None, memory_pool: MemoryPool | None = None, -) -> DoubleArray | Expression: ... +) -> NumericArray | _DecimalArray | Expression: ... def skew( array: _ScalarOrArray | _ArrayLike | Expression, /, From abc5d5f3b58923fd04b3ad1340c2741fb675bb10 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Fri, 20 Nov 2026 09:12:15 +0100 Subject: [PATCH 11/33] Review Arithmetic Arithmetic functions stubs --- python/pyarrow-stubs-tests/test_compute.py | 19 ++- python/pyarrow-stubs/compute.pyi | 164 ++++++++++----------- 2 files changed, 95 insertions(+), 88 deletions(-) diff --git a/python/pyarrow-stubs-tests/test_compute.py b/python/pyarrow-stubs-tests/test_compute.py index 7a7921f55407..0e0c74e45b05 100644 --- a/python/pyarrow-stubs-tests/test_compute.py +++ b/python/pyarrow-stubs-tests/test_compute.py @@ -194,6 +194,21 @@ def test_element_wise_functions() -> None: check(assert_type(pc.random(3), pa.DoubleArray), pa.DoubleArray) + check(pc.abs([1, 2]), pa.Int64Array) + check(pc.abs((1.0, -2.0)), pa.DoubleArray) + check(pc.abs(1), pa.Int64Scalar) + check(pc.abs_checked(-2.0), pa.DoubleScalar) + check(pc.add(-2.0, 1.0), pa.DoubleScalar) + check(pc.add_checked([2.0, 3.0], 1), pa.DoubleArray) + check(pc.exp(2.0), pa.DoubleScalar) + check(pc.exp([1, 2]), pa.DoubleArray) + check(pc.divide([1, 2, 3], 1), pa.Int64Array) + check(pc.divide(arr, 2.0), pa.Array) + check(pc.hypot([1, 2, 3], 1), pa.DoubleArray) + check(pc.modulo([7, -7], [3, 3]), pa.Int64Array) + check(pc.power(arr, 2), pa.Array) + check(pc.sqrt(pa.chunked_array([[1], [2, 3]])), pa.ChunkedArray) + # Python lists and other iterables are accepted where the stubs list them. check(pc.round((1.5, 2.5)), pa.Array) check(pc.round([1.5, 2.5]), pa.Array) @@ -206,10 +221,6 @@ def test_element_wise_functions() -> None: pa.Array) check(pc.if_else(pc.field("a") > 1, 1, 2), pc.Expression) - # Python literals are accepted next to arrays. - check(pc.power(arr, 2), pa.Array) - check(pc.divide(arr, 2.0), pa.Array) - def test_agg_functions() -> None: import numpy as np diff --git a/python/pyarrow-stubs/compute.pyi b/python/pyarrow-stubs/compute.pyi index 2571a655e040..5182e61325b2 100644 --- a/python/pyarrow-stubs/compute.pyi +++ b/python/pyarrow-stubs/compute.pyi @@ -254,32 +254,23 @@ _NumericOrTemporalScalar: TypeAlias = _NumericScalar | _TemporalScalar # pyarrow.array() and most of the API return plain Array and ChunkedArray # instances, as these classes aren't generic. So the compute functions accept # any Array or ChunkedArray, and only the return types say which kind of array -# the result is, e.g. a StringArray for a string input. The ChunkedArray of a -# chunked input is the same for every kind. +# the result is, e.g. a StringArray for a string input. _ArrayOrChunkedArray: TypeAlias = Array | ChunkedArray _ScalarOrArray: TypeAlias = Scalar | Array | ChunkedArray _ArrayLike: TypeAlias = ( list[Any] | tuple[Any, ...] | NDArray[Any] | Array | ChunkedArray ) +_ComputeInput: TypeAlias = _ScalarOrArray | _ArrayLike | Expression _DecimalArray: TypeAlias = ( Decimal32Array | Decimal64Array | Decimal128Array | Decimal256Array ) # NumericArray includes the date, time, timestamp and duration arrays. -_NumericArray: TypeAlias = NumericArray | _DecimalArray | ChunkedArray +_NumericArray: TypeAlias = NumericArray | _DecimalArray _NumericOrDurationArray: TypeAlias = _NumericArray _NumericOrTemporalArray: TypeAlias = _NumericArray | MonthDayNanoIntervalArray -_IntegerArray: TypeAlias = IntegerArray | ChunkedArray -_FloatArray: TypeAlias = FloatingPointArray | ChunkedArray -_BooleanArray: TypeAlias = BooleanArray | ChunkedArray -_StringArray: TypeAlias = ( - StringArray | LargeStringArray | StringViewArray | ChunkedArray -) +_StringArray: TypeAlias = StringArray | LargeStringArray | StringViewArray _BinaryArray: TypeAlias = ( - BinaryArray - | LargeBinaryArray - | BinaryViewArray - | FixedSizeBinaryArray - | ChunkedArray + BinaryArray | LargeBinaryArray | BinaryViewArray | FixedSizeBinaryArray ) _StringOrBinaryArray: TypeAlias = _StringArray | _BinaryArray _TemporalArray: TypeAlias = ( @@ -290,9 +281,7 @@ _TemporalArray: TypeAlias = ( | TimestampArray | DurationArray | MonthDayNanoIntervalArray - | ChunkedArray ) -_ListArray: TypeAlias = BaseListArray | ChunkedArray # =============================== Aggregations ======================================== def all( @@ -481,95 +470,102 @@ def variance( # ========================= Arithmetic functions ========================= def abs( - x: _ScalarOrArray | Expression | float, + x: _ComputeInput | float, /, *, memory_pool: MemoryPool | None = None, -) -> _NumericOrDurationScalar | _NumericOrDurationArray | Expression: ... +) -> _NumericOrDurationScalar | _NumericOrDurationArray | ChunkedArray | Expression: ... abs_checked = _clone_signature(abs) def add( - x: _ScalarOrArray | _ArrayLike | int | Expression, - y: _ScalarOrArray | _ArrayLike | int | Expression, + x: _ComputeInput | float, + y: _ComputeInput | float, /, *, memory_pool: MemoryPool | None = None, -) -> _NumericOrTemporalScalar | _NumericOrTemporalArray | Expression: ... +) -> _NumericOrTemporalScalar | _NumericOrTemporalArray | ChunkedArray | Expression: ... add_checked = _clone_signature(add) def divide( - x: _ScalarOrArray | Expression | float, - y: _ScalarOrArray | Expression | float, + x: _ComputeInput | float, + y: _ComputeInput | float, /, *, memory_pool: MemoryPool | None = None, -) -> _NumericOrTemporalScalar | _NumericOrTemporalArray | Expression: ... +) -> _NumericOrTemporalScalar | _NumericOrTemporalArray | ChunkedArray | Expression: ... divide_checked = _clone_signature(divide) def exp( - exponent: _ScalarOrArray | Expression, + exponent: _ComputeInput | float, /, *, memory_pool: MemoryPool | None = None, -) -> _FloatArray | DoubleArray | _FloatScalar | DoubleScalar | Expression: ... +) -> ( + FloatingPointArray + | ChunkedArray + | DoubleArray + | _FloatScalar + | DoubleScalar + | Expression +): ... expm1 = _clone_signature(exp) def hypot( - x: _ScalarOrArray | float | Expression, - y: _ScalarOrArray | float | Expression, + x: _ComputeInput | float, + y: _ComputeInput | float, /, *, memory_pool: MemoryPool | None = None, -) -> _FloatScalar | _FloatArray | Expression: ... +) -> _FloatScalar | FloatingPointArray | ChunkedArray | Expression: ... def modulo( - dividend: _ScalarOrArray | float | Expression, - divisor: _ScalarOrArray | float | Expression, + dividend: _ComputeInput | float, + divisor: _ComputeInput | float, /, *, memory_pool: MemoryPool | None = None, -) -> _NumericScalar | _NumericArray | Expression: ... +) -> _NumericScalar | _NumericArray | ChunkedArray | Expression: ... modulo_checked = _clone_signature(modulo) multiply = _clone_signature(add) multiply_checked = _clone_signature(add) def negate( - x: _ScalarOrArray | Expression | float, + x: _ComputeInput | float, /, *, memory_pool: MemoryPool | None = None, -) -> _NumericOrDurationScalar | _NumericOrDurationArray | Expression: ... +) -> _NumericOrDurationScalar | _NumericOrDurationArray | ChunkedArray | Expression: ... negate_checked = _clone_signature(negate) def power( - base: _ScalarOrArray | Expression | float, - exponent: _ScalarOrArray | Expression | float, + base: _ComputeInput | float, + exponent: _ComputeInput | float, /, *, memory_pool: MemoryPool | None = None, -) -> _NumericScalar | _NumericArray | Expression: ... +) -> _NumericScalar | _NumericArray | ChunkedArray | Expression: ... power_checked = _clone_signature(power) remainder = _clone_signature(modulo) remainder_checked = _clone_signature(modulo) def sign( - x: _ScalarOrArray | Expression | float, + x: _ComputeInput | float, /, *, memory_pool: MemoryPool | None = None, ) -> Int8Scalar | _FloatScalar | NumericArray | ChunkedArray | Expression: ... def sqrt( - x: _ScalarOrArray | Expression | float, + x: _ComputeInput | float, /, *, memory_pool: MemoryPool | None = None, -) -> _FloatArray | _FloatScalar | Expression: ... +) -> FloatingPointArray | _FloatScalar | ChunkedArray | Expression: ... sqrt_checked = _clone_signature(sqrt) subtract = _clone_signature(add) @@ -582,13 +578,13 @@ def bit_wise_and( /, *, memory_pool: MemoryPool | None = None, -) -> _NumericScalar | _NumericArray | Expression: ... +) -> _NumericScalar | _NumericArray | ChunkedArray | Expression: ... def bit_wise_not( x: _ScalarOrArray | Expression | float, /, *, memory_pool: MemoryPool | None = None, -) -> _NumericScalar | _NumericArray | Expression: ... +) -> _NumericScalar | _NumericArray | ChunkedArray | Expression: ... bit_wise_or = _clone_signature(bit_wise_and) bit_wise_xor = _clone_signature(bit_wise_and) @@ -603,7 +599,7 @@ def ceil( /, *, memory_pool: MemoryPool | None = None, -) -> _FloatScalar | _FloatArray | Expression: ... +) -> _FloatScalar | FloatingPointArray | ChunkedArray | Expression: ... floor = _clone_signature(ceil) @@ -615,7 +611,7 @@ def round( *, options: RoundOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _NumericScalar | _NumericArray | Expression: ... +) -> _NumericScalar | _NumericArray | ChunkedArray | Expression: ... def round_to_multiple( x: _ScalarOrArray | Iterable[Any] | Expression | float, /, @@ -624,7 +620,7 @@ def round_to_multiple( *, options: RoundToMultipleOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _NumericScalar | _NumericArray | Expression: ... +) -> _NumericScalar | _NumericArray | ChunkedArray | Expression: ... def round_binary( x: _ScalarOrArray | Iterable[Any] | float | Expression, s: _ScalarOrArray | int | Expression, @@ -633,7 +629,7 @@ def round_binary( *, options: RoundBinaryOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _NumericScalar | _NumericArray | Expression: ... +) -> _NumericScalar | _NumericArray | ChunkedArray | Expression: ... trunc = _clone_signature(ceil) @@ -643,7 +639,7 @@ def ln( /, *, memory_pool: MemoryPool | None = None, -) -> _FloatScalar | _FloatArray | Expression: ... +) -> _FloatScalar | FloatingPointArray | ChunkedArray | Expression: ... ln_checked = _clone_signature(ln) log10 = _clone_signature(ln) @@ -659,7 +655,7 @@ def logb( /, *, memory_pool: MemoryPool | None = None, -) -> _FloatScalar | _FloatArray | Expression: ... +) -> _FloatScalar | FloatingPointArray | ChunkedArray | Expression: ... logb_checked = _clone_signature(logb) @@ -676,7 +672,7 @@ def atan2( /, *, memory_pool: MemoryPool | None = None, -) -> _FloatScalar | _FloatArray | Expression: ... +) -> _FloatScalar | FloatingPointArray | ChunkedArray | Expression: ... cos = _clone_signature(ln) cos_checked = _clone_signature(ln) @@ -702,7 +698,7 @@ def equal( /, *, memory_pool: MemoryPool | None = None, -) -> BooleanScalar | _BooleanArray | Expression: ... +) -> BooleanScalar | BooleanArray | ChunkedArray | Expression: ... greater = _clone_signature(equal) greater_equal = _clone_signature(equal) @@ -726,7 +722,7 @@ def and_( /, *, memory_pool: MemoryPool | None = None, -) -> BooleanScalar | _BooleanArray | Expression: ... +) -> BooleanScalar | BooleanArray | ChunkedArray | Expression: ... and_kleene = _clone_signature(and_) and_not = _clone_signature(and_) @@ -737,7 +733,7 @@ def invert( /, *, memory_pool: MemoryPool | None = None, -) -> BooleanScalar | _BooleanArray | Expression: ... +) -> BooleanScalar | BooleanArray | ChunkedArray | Expression: ... or_ = _clone_signature(and_) or_kleene = _clone_signature(and_) @@ -749,7 +745,7 @@ def ascii_is_alnum( /, *, memory_pool: MemoryPool | None = None, -) -> BooleanScalar | _BooleanArray | Expression: ... +) -> BooleanScalar | BooleanArray | ChunkedArray | Expression: ... ascii_is_alpha = _clone_signature(ascii_is_alnum) ascii_is_decimal = _clone_signature(ascii_is_alnum) @@ -776,7 +772,7 @@ def ascii_capitalize( /, *, memory_pool: MemoryPool | None = None, -) -> _StringScalar | _StringArray | Expression: ... +) -> _StringScalar | _StringArray | ChunkedArray | Expression: ... ascii_lower = _clone_signature(ascii_capitalize) ascii_reverse = _clone_signature(ascii_capitalize) @@ -798,7 +794,7 @@ def binary_repeat( /, *, memory_pool: MemoryPool | None = None, -) -> _StringOrBinaryScalar | _StringOrBinaryArray | Expression: ... +) -> _StringOrBinaryScalar | _StringOrBinaryArray | ChunkedArray | Expression: ... def binary_replace_slice( strings: _ScalarOrArray | Expression, /, @@ -808,13 +804,13 @@ def binary_replace_slice( *, options: ReplaceSliceOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _StringOrBinaryScalar | _StringOrBinaryArray | Expression: ... +) -> _StringOrBinaryScalar | _StringOrBinaryArray | ChunkedArray | Expression: ... def binary_reverse( strings: _ScalarOrArray | Expression, /, *, memory_pool: MemoryPool | None = None, -) -> _BinaryScalar | _BinaryArray | Expression: ... +) -> _BinaryScalar | _BinaryArray | ChunkedArray | Expression: ... def replace_substring( strings: _ScalarOrArray | Expression, /, @@ -824,7 +820,7 @@ def replace_substring( max_replacements: int | None = None, options: ReplaceSubstringOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _StringScalar | _StringArray | Expression: ... +) -> _StringScalar | _StringArray | ChunkedArray | Expression: ... replace_substring_regex = _clone_signature(replace_substring) @@ -833,7 +829,7 @@ def utf8_capitalize( /, *, memory_pool: MemoryPool | None = None, -) -> _StringScalar | _StringArray | Expression: ... +) -> _StringScalar | _StringArray | ChunkedArray | Expression: ... def utf8_length( strings: _ScalarOrArray | Expression, /, @@ -854,7 +850,7 @@ def utf8_replace_slice( *, options: ReplaceSliceOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _StringScalar | _StringArray | Expression: ... +) -> _StringScalar | _StringArray | ChunkedArray | Expression: ... utf8_reverse = _clone_signature(utf8_capitalize) utf8_swapcase = _clone_signature(utf8_capitalize) @@ -868,7 +864,7 @@ def utf8_normalize( *, options: Utf8NormalizeOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _StringScalar | _StringArray | Expression: ... +) -> _StringScalar | _StringArray | ChunkedArray | Expression: ... # ========================= String padding ========================= def ascii_center( @@ -880,7 +876,7 @@ def ascii_center( *, options: PadOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _StringScalar | _StringArray | Expression: ... +) -> _StringScalar | _StringArray | ChunkedArray | Expression: ... ascii_lpad = _clone_signature(ascii_center) ascii_rpad = _clone_signature(ascii_center) @@ -896,7 +892,7 @@ def utf8_zero_fill( *, options: ZeroFillOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _StringScalar | _StringArray | Expression: ... +) -> _StringScalar | _StringArray | ChunkedArray | Expression: ... utf8_zfill = utf8_zero_fill @@ -908,13 +904,13 @@ def ascii_ltrim( *, options: TrimOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _StringScalar | _StringArray | Expression: ... +) -> _StringScalar | _StringArray | ChunkedArray | Expression: ... def ascii_ltrim_whitespace( strings: _ScalarOrArray | Expression, /, *, memory_pool: MemoryPool | None = None, -) -> _StringScalar | _StringArray | Expression: ... +) -> _StringScalar | _StringArray | ChunkedArray | Expression: ... ascii_rtrim = _clone_signature(ascii_ltrim) ascii_rtrim_whitespace = _clone_signature(ascii_ltrim_whitespace) @@ -936,7 +932,7 @@ def ascii_split_whitespace( reverse: bool = False, options: SplitOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _ListScalar | _ListArray | Expression: ... +) -> _ListScalar | BaseListArray | ChunkedArray | Expression: ... def split_pattern( strings: _ScalarOrArray | Expression, /, @@ -946,7 +942,7 @@ def split_pattern( reverse: bool = False, options: SplitOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _ListScalar | _ListArray | Expression: ... +) -> _ListScalar | BaseListArray | ChunkedArray | Expression: ... split_pattern_regex = _clone_signature(split_pattern) utf8_split_whitespace = _clone_signature(ascii_split_whitespace) @@ -970,14 +966,14 @@ def binary_join( /, *, memory_pool: MemoryPool | None = None, -) -> _StringOrBinaryScalar | _StringOrBinaryArray | Expression: ... +) -> _StringOrBinaryScalar | _StringOrBinaryArray | ChunkedArray | Expression: ... def binary_join_element_wise( *strings: str | bytes | _ScalarOrArray | Iterable[Any] | Expression, null_handling: _NullHandling = "emit_null", null_replacement: str = "", options: JoinOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _StringOrBinaryScalar | _StringOrBinaryArray | Expression: ... +) -> _StringOrBinaryScalar | _StringOrBinaryArray | ChunkedArray | Expression: ... # ========================= String Slicing ========================= def binary_slice( @@ -989,7 +985,7 @@ def binary_slice( *, options: SliceOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _BinaryScalar | _BinaryArray | Expression: ... +) -> _BinaryScalar | _BinaryArray | ChunkedArray | Expression: ... def utf8_slice_codeunits( strings: _ScalarOrArray | Expression, /, @@ -999,7 +995,7 @@ def utf8_slice_codeunits( *, options: SliceOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _StringScalar | _StringArray | Expression: ... +) -> _StringScalar | _StringArray | ChunkedArray | Expression: ... # ========================= Containment tests ========================= def count_substring( @@ -1024,7 +1020,7 @@ def ends_with( ignore_case: bool = False, options: MatchSubstringOptions | None = None, memory_pool: MemoryPool | None = None, -) -> BooleanScalar | _BooleanArray | Expression: ... +) -> BooleanScalar | BooleanArray | ChunkedArray | Expression: ... find_substring = _clone_signature(count_substring) find_substring_regex = _clone_signature(count_substring) @@ -1046,7 +1042,7 @@ def is_in( skip_nulls: bool = False, options: SetLookupOptions | None = None, memory_pool: MemoryPool | None = None, -) -> BooleanScalar | _BooleanArray | Expression: ... +) -> BooleanScalar | BooleanArray | ChunkedArray | Expression: ... match_like = _clone_signature(ends_with) match_substring = _clone_signature(ends_with) @@ -1069,7 +1065,7 @@ def is_finite( /, *, memory_pool: MemoryPool | None = None, -) -> BooleanScalar | _BooleanArray | Expression: ... +) -> BooleanScalar | BooleanArray | ChunkedArray | Expression: ... is_inf = _clone_signature(is_finite) is_nan = _clone_signature(is_finite) @@ -1081,13 +1077,13 @@ def is_null( nan_is_null: bool = False, options: NullOptions | None = None, memory_pool: MemoryPool | None = None, -) -> BooleanScalar | _BooleanArray | Expression: ... +) -> BooleanScalar | BooleanArray | ChunkedArray | Expression: ... def is_valid( values: _ScalarOrArray | Expression | _ArrayLike, /, *, memory_pool: MemoryPool | None = None, -) -> BooleanScalar | _BooleanArray | Expression: ... +) -> BooleanScalar | BooleanArray | ChunkedArray | Expression: ... true_unless_null = _clone_signature(is_valid) @@ -1149,7 +1145,7 @@ def ceil_temporal( calendar_based_origin: bool = False, options: RoundTemporalOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _TemporalScalar | _TemporalArray | Expression: ... +) -> _TemporalScalar | _TemporalArray | ChunkedArray | Expression: ... floor_temporal = _clone_signature(ceil_temporal) round_temporal = _clone_signature(ceil_temporal) @@ -1225,7 +1221,7 @@ def is_dst( /, *, memory_pool: MemoryPool | None = None, -) -> BooleanScalar | _BooleanArray | Expression: ... +) -> BooleanScalar | BooleanArray | ChunkedArray | Expression: ... def iso_week( values: _ScalarOrArray | Expression, /, @@ -1240,7 +1236,7 @@ def is_leap_year( /, *, memory_pool: MemoryPool | None = None, -) -> BooleanScalar | _BooleanArray | Expression: ... +) -> BooleanScalar | BooleanArray | ChunkedArray | Expression: ... microsecond = _clone_signature(iso_week) millisecond = _clone_signature(iso_week) @@ -1368,7 +1364,7 @@ def cumulative_sum( skip_nulls: bool = False, options: CumulativeOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _NumericArray | Expression: ... +) -> _NumericArray | ChunkedArray | Expression: ... cumulative_sum_checked = _clone_signature(cumulative_sum) cumulative_prod = _clone_signature(cumulative_sum) @@ -1386,7 +1382,7 @@ def winsorize( *, options: WinsorizeOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _NumericArray | Expression: ... +) -> _NumericArray | ChunkedArray | Expression: ... # ========================= Associative transforms ========================= def dictionary_encode( @@ -1458,7 +1454,7 @@ def inverse_permutation( *, options: InversePermutationOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _IntegerArray | Expression: ... +) -> IntegerArray | ChunkedArray | Expression: ... def scatter( values: _ArrayOrChunkedArray | Expression, indices: _ArrayOrChunkedArray | Expression, @@ -1607,7 +1603,7 @@ def list_slice( *, options: ListSliceOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _ListArray | Expression: ... +) -> BaseListArray | ChunkedArray | Expression: ... def map_lookup( container: _ScalarOrArray | Expression, /, @@ -1656,6 +1652,6 @@ def pairwise_diff( *, options: PairwiseOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _NumericOrTemporalArray | Expression: ... +) -> _NumericOrTemporalArray | ChunkedArray | Expression: ... pairwise_diff_checked = _clone_signature(pairwise_diff) From e204900c20c9d432bc62ef85eab305c819122b29 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Fri, 20 Nov 2026 11:51:31 +0100 Subject: [PATCH 12/33] Review rounding, log and trig stubs, list ChunkedArray in signatures, clean up the tests --- python/pyarrow-stubs-tests/test_compute.py | 75 ++++++++++++++++++---- python/pyarrow-stubs/compute.pyi | 45 +++++++------ 2 files changed, 89 insertions(+), 31 deletions(-) diff --git a/python/pyarrow-stubs-tests/test_compute.py b/python/pyarrow-stubs-tests/test_compute.py index 0e0c74e45b05..639b75a5d35c 100644 --- a/python/pyarrow-stubs-tests/test_compute.py +++ b/python/pyarrow-stubs-tests/test_compute.py @@ -16,6 +16,7 @@ # under the License. from collections.abc import Hashable +from decimal import Decimal from types import EllipsisType from typing import TYPE_CHECKING, TypeAlias @@ -40,12 +41,14 @@ def test_expression() -> None: + # Field references and literals field = pc.field("a") check(assert_type(field, pc.Expression), pc.Expression) check(assert_type(pc.field("a", "b"), pc.Expression), pc.Expression) check(assert_type(pc.field(("a", 0)), pc.Expression), pc.Expression) check(assert_type(pc.scalar(1), pc.Expression), pc.Expression) + # Operators and methods build expressions check(assert_type(field > 1, pc.Expression), pc.Expression) check(assert_type(field == 1, pc.Expression), pc.Expression) check(assert_type(field != 1, pc.Expression), pc.Expression) @@ -61,7 +64,7 @@ def test_expression() -> None: pc.Expression) check(assert_type(field.equals(pc.field("a")), bool), bool) - # Calling a compute function with an expression builds an expression. + # Compute functions on an expression build an expression check(pc.count(field), pc.Expression) check(pc.mean(field), pc.Expression) @@ -106,18 +109,27 @@ def test_functions() -> None: def test_options() -> None: + # Cast options check(assert_type(pc.CastOptions.safe(pa.int64()), pc.CastOptions), pc.CastOptions) check(assert_type(pc.CastOptions.safe().is_safe(), bool), bool) + check(assert_type(pc.ScalarAggregateOptions(skip_nulls=False), pc.ScalarAggregateOptions), pc.ScalarAggregateOptions) + + # Sort keys refer to a column by name or index check(assert_type(pc.SortOptions([("a", "ascending", "at_start")]), pc.SortOptions), pc.SortOptions) check(assert_type(pc.SortOptions([(0, "ascending", "at_start")]), pc.SortOptions), pc.SortOptions) + check(assert_type(pc.SelectKOptions(1, [("a", "ascending", "at_end")]), + pc.SelectKOptions), + pc.SelectKOptions) + + # Struct fields: metadata may be None, fields by name or index md = pa.KeyValueMetadata({"k": "v"}) check(assert_type(pc.MakeStructOptions(["a", "b"], field_metadata=[None, md]), pc.MakeStructOptions), @@ -126,9 +138,8 @@ def test_options() -> None: pc.StructFieldOptions) check(assert_type(pc.StructFieldOptions(["a", "b"]), pc.StructFieldOptions), pc.StructFieldOptions) - check(assert_type(pc.SelectKOptions(1, [("a", "ascending", "at_end")]), - pc.SelectKOptions), - pc.SelectKOptions) + + # Other parameter types: ChunkedArray value set, hashable seed, Literals check(assert_type(pc.SetLookupOptions(pa.chunked_array([[1, 2]])), pc.SetLookupOptions), pc.SetLookupOptions) @@ -137,6 +148,8 @@ def test_options() -> None: check(assert_type(pc.SearchSortedOptions(side="right"), pc.SearchSortedOptions), pc.SearchSortedOptions) + + # Options can be serialized options = pc.RoundOptions(2, round_mode="half_up") check(assert_type(options.serialize(), Buffer), Buffer) @@ -150,6 +163,7 @@ def test_array_wise_functions() -> None: arr = pa.array([3, 1, 2]) table = pa.table({"a": [3, 1, 2]}) + # Sorts and selections check(assert_type(pc.array_sort_indices(arr), pa.UInt64Array | pc.Expression), pa.UInt64Array) check(assert_type(pc.sort_indices(table, [("a", "descending")]), @@ -167,6 +181,7 @@ def test_array_wise_functions() -> None: check(assert_type(pc.value_counts(arr), pa.StructArray | pc.Expression), pa.StructArray) + # Filters keep the input kind: table, array or expression mask = pa.array([True, False, True]) check(assert_type(pc.filter(table, mask), _Filtered), pa.Table) check(assert_type(pc.drop_null(table), _Filtered), pa.Table) @@ -174,7 +189,7 @@ def test_array_wise_functions() -> None: _Filtered), pc.Expression) - # Python lists and other iterables are accepted where the stubs list them. + # Python lists and tuples accepted check(assert_type(pc.partition_nth_indices([3, 1, 2], pivot=1), pa.UInt64Array | pc.Expression), pa.UInt64Array) @@ -187,6 +202,8 @@ def test_array_wise_functions() -> None: pc.top_k_unstable(arr, "2") # type: ignore[arg-type] pc.sort_indices(table, [("a", "up")]) # type: ignore[list-item] pc.cumulative_sum(range(3)) # type: ignore[arg-type] + # TODO: test invalid code once the scalar stubs are annotated + # pc.variance(range(3)), pc.round("abc") def test_element_wise_functions() -> None: @@ -194,33 +211,60 @@ def test_element_wise_functions() -> None: check(assert_type(pc.random(3), pa.DoubleArray), pa.DoubleArray) + # Arithmetic: Python literals, lists and tuples accepted check(pc.abs([1, 2]), pa.Int64Array) - check(pc.abs((1.0, -2.0)), pa.DoubleArray) + check(pc.abs((1.5, -2.5)), pa.DoubleArray) check(pc.abs(1), pa.Int64Scalar) - check(pc.abs_checked(-2.0), pa.DoubleScalar) - check(pc.add(-2.0, 1.0), pa.DoubleScalar) - check(pc.add_checked([2.0, 3.0], 1), pa.DoubleArray) - check(pc.exp(2.0), pa.DoubleScalar) + check(pc.abs_checked(-2.5), pa.DoubleScalar) + check(pc.add(-2.5, 1.5), pa.DoubleScalar) + check(pc.add_checked([2.5, 3.5], 1), pa.DoubleArray) + check(pc.exp(2.5), pa.DoubleScalar) check(pc.exp([1, 2]), pa.DoubleArray) check(pc.divide([1, 2, 3], 1), pa.Int64Array) - check(pc.divide(arr, 2.0), pa.Array) + check(pc.divide(arr, 2.5), pa.Array) check(pc.hypot([1, 2, 3], 1), pa.DoubleArray) check(pc.modulo([7, -7], [3, 3]), pa.Int64Array) check(pc.power(arr, 2), pa.Array) check(pc.sqrt(pa.chunked_array([[1], [2, 3]])), pa.ChunkedArray) - # Python lists and other iterables are accepted where the stubs list them. + # Bit-wise functions + check(pc.bit_wise_and([1, 1], [1, 1]), pa.Int64Array) + check(pc.bit_wise_not([1, 1]), pa.Int64Array) + + # Rounding returns floats, or decimals for decimal input + check(pc.ceil(1.5), pa.DoubleScalar) + check(pc.floor([1, 2]), pa.DoubleArray) + check(pc.trunc(pa.scalar(Decimal("1.5"))), pa.Decimal128Scalar) + check(pc.trunc(pa.array([Decimal("1.5")])), pa.Decimal128Array) + + # Logarithms return floats + check(pc.ln(pa.array([Decimal("1.5")])), pa.DoubleArray) + + # Trigonometric functions return floats, also for decimal input + # Python lists and tuples accepted + check(pc.sin([1, 2]), pa.DoubleArray) + check(pc.acos(0.5), pa.DoubleScalar) + check(pc.atan2(1.5, [1, 2]), pa.DoubleArray) + check(pc.cosh(pa.array([Decimal("1.5")])), pa.DoubleArray) + + # Python lists and tuples accepted check(pc.round((1.5, 2.5)), pa.Array) check(pc.round([1.5, 2.5]), pa.Array) check(pc.binary_repeat(pa.array(["a"]), (2,)), pa.Array) check(pc.binary_join_element_wise(["a", "b"], ["c", "d"], "-"), pa.Array) check(pc.struct_field(pa.array([{"a": 1}]), ("a",)), pa.Array) + check(pc.acos([1.1, 1.1]), pa.DoubleArray) + check(pc.atan2([1.1, 1.1], [1.1, 1.1]), pa.DoubleArray) + # An Expression as the first argument gives an Expression selected = pc.if_else([True, False], [1, 2], [3, 4]) check(assert_type(selected, pa.Scalar | pa.Array | pa.ChunkedArray | pc.Expression), pa.Array) check(pc.if_else(pc.field("a") > 1, 1, 2), pc.Expression) + # TODO: test invalid code once the scalar stubs are annotated + # pc.bit_wise_and(1.0, 1.0), pc.bit_wise_not(1.0) + def test_agg_functions() -> None: import numpy as np @@ -228,19 +272,26 @@ def test_agg_functions() -> None: arr = pa.array([3, 1, 2]) scalar = pa.scalar(1) + # Scalar input accepted check(pc.count(scalar), pa.Int64Scalar) check(pc.count_distinct(scalar), pa.Int64Scalar) check(pc.first(scalar), pa.Int64Scalar) check(pc.last(scalar), pa.Int64Scalar) check(pc.first_last((1, 2)), pa.StructScalar) check(pc.first_last(scalar), pa.StructScalar) + + # Quantile returns doubles, or the input type for "lower", "higher", "nearest" check(assert_type(pc.quantile(arr, q=[0.25, 0.75]), _Quantile), pa.DoubleArray) check(assert_type(pc.quantile(arr, interpolation="lower"), _Quantile), pa.Int64Array) check(assert_type(pc.mode(arr, n=2), pa.StructArray | pc.Expression), pa.StructArray) + + # Python lists, tuples and NumPy arrays accepted check(pc.variance([1, 2, 3]), pa.DoubleScalar) check(pc.variance((1, 2, 3)), pa.DoubleScalar) check(pc.variance(np.array([1.0, 2.0, 3.0])), pa.DoubleScalar) + + # An Expression as input gives an Expression check(pc.mean(arr), pa.DoubleScalar) check(pc.mean(pc.field(0)), pc.Expression) diff --git a/python/pyarrow-stubs/compute.pyi b/python/pyarrow-stubs/compute.pyi index 5182e61325b2..7657b07c02ce 100644 --- a/python/pyarrow-stubs/compute.pyi +++ b/python/pyarrow-stubs/compute.pyi @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -from collections.abc import Callable, Hashable, Iterable, Sequence +from collections.abc import Callable, Hashable, Sequence from typing import Any, ParamSpec, TypeAlias, TypeVar from numpy.typing import NDArray @@ -331,7 +331,7 @@ def first( memory_pool: MemoryPool | None = None, ) -> Scalar | Expression: ... def first_last( - array: _ScalarOrArray | Iterable[Any] | Expression, + array: _ComputeInput, /, *, skip_nulls: bool = True, @@ -573,14 +573,14 @@ subtract_checked = _clone_signature(add) # ========================= Bit-wise functions ========================= def bit_wise_and( - x: _ScalarOrArray | Expression | float, - y: _ScalarOrArray | Expression | float, + x: _ComputeInput | int, + y: _ComputeInput | int, /, *, memory_pool: MemoryPool | None = None, ) -> _NumericScalar | _NumericArray | ChunkedArray | Expression: ... def bit_wise_not( - x: _ScalarOrArray | Expression | float, + x: _ComputeInput | int, /, *, memory_pool: MemoryPool | None = None, @@ -595,16 +595,23 @@ shift_right_checked = _clone_signature(bit_wise_and) # ========================= Rounding functions ========================= def ceil( - x: _ScalarOrArray | Expression | float, + x: _ComputeInput | float, /, *, memory_pool: MemoryPool | None = None, -) -> _FloatScalar | FloatingPointArray | ChunkedArray | Expression: ... +) -> ( + _FloatScalar + | _DecimalScalar + | FloatingPointArray + | _DecimalArray + | ChunkedArray + | Expression +): ... floor = _clone_signature(ceil) def round( - x: _ScalarOrArray | Iterable[Any] | Expression | float, + x: _ComputeInput | float, /, ndigits: int = 0, round_mode: _RoundMode = "half_to_even", @@ -613,7 +620,7 @@ def round( memory_pool: MemoryPool | None = None, ) -> _NumericScalar | _NumericArray | ChunkedArray | Expression: ... def round_to_multiple( - x: _ScalarOrArray | Iterable[Any] | Expression | float, + x: _ComputeInput | float, /, multiple: float | Scalar = 1.0, round_mode: _RoundMode = "half_to_even", @@ -622,8 +629,8 @@ def round_to_multiple( memory_pool: MemoryPool | None = None, ) -> _NumericScalar | _NumericArray | ChunkedArray | Expression: ... def round_binary( - x: _ScalarOrArray | Iterable[Any] | float | Expression, - s: _ScalarOrArray | int | Expression, + x: _ComputeInput | float, + s: _ComputeInput | int, /, round_mode: _RoundMode = "half_to_even", *, @@ -635,7 +642,7 @@ trunc = _clone_signature(ceil) # ========================= Logarithmic functions ========================= def ln( - x: _ScalarOrArray | Expression | float, + x: _ComputeInput | float, /, *, memory_pool: MemoryPool | None = None, @@ -650,8 +657,8 @@ log2 = _clone_signature(ln) log2_checked = _clone_signature(ln) def logb( - x: _ScalarOrArray | float | Expression, - b: _ScalarOrArray | float | Expression, + x: _ComputeInput | float, + b: _ComputeInput | float, /, *, memory_pool: MemoryPool | None = None, @@ -667,8 +674,8 @@ asin_checked = _clone_signature(ln) atan = _clone_signature(ln) def atan2( - y: _ScalarOrArray | float | Expression, - x: _ScalarOrArray | float | Expression, + y: _ComputeInput | float, + x: _ComputeInput | float, /, *, memory_pool: MemoryPool | None = None, @@ -790,7 +797,7 @@ def binary_length( ): ... def binary_repeat( strings: _ScalarOrArray | Expression, - num_repeats: int | _ArrayOrChunkedArray | Iterable[int | None] | Expression, + num_repeats: int | _ComputeInput, /, *, memory_pool: MemoryPool | None = None, @@ -968,7 +975,7 @@ def binary_join( memory_pool: MemoryPool | None = None, ) -> _StringOrBinaryScalar | _StringOrBinaryArray | ChunkedArray | Expression: ... def binary_join_element_wise( - *strings: str | bytes | _ScalarOrArray | Iterable[Any] | Expression, + *strings: str | bytes | _ComputeInput, null_handling: _NullHandling = "emit_null", null_replacement: str = "", options: JoinOptions | None = None, @@ -1491,7 +1498,7 @@ def array_sort_indices( memory_pool: MemoryPool | None = None, ) -> UInt64Array | Expression: ... def partition_nth_indices( - array: _ArrayOrChunkedArray | Iterable[Any] | Expression, + array: _ArrayOrChunkedArray | _ArrayLike | Expression, /, pivot: int, *, From 0b73298d352e78098e46d673fe2cce09e71018ae Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Fri, 20 Nov 2026 12:31:59 +0100 Subject: [PATCH 13/33] Update _ArrayLike type alias --- python/pyarrow-stubs-tests/test_compute.py | 4 ++++ python/pyarrow-stubs/compute.pyi | 21 +++++++++++---------- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/python/pyarrow-stubs-tests/test_compute.py b/python/pyarrow-stubs-tests/test_compute.py index 639b75a5d35c..25325f3d2aa5 100644 --- a/python/pyarrow-stubs-tests/test_compute.py +++ b/python/pyarrow-stubs-tests/test_compute.py @@ -198,6 +198,10 @@ def test_array_wise_functions() -> None: check(assert_type(taken, pa.Array | pa.ChunkedArray | pa.RecordBatch | pa.Table), pa.Array) + # Replacements as an array or a Python list + check(pc.replace_with_mask(arr, mask, pa.array([10, 30])), pa.Int64Array) + check(pc.replace_with_mask(arr, mask, [10, 30]), pa.Int64Array) + if TYPE_CHECKING: pc.top_k_unstable(arr, "2") # type: ignore[arg-type] pc.sort_indices(table, [("a", "up")]) # type: ignore[list-item] diff --git a/python/pyarrow-stubs/compute.pyi b/python/pyarrow-stubs/compute.pyi index 7657b07c02ce..7b14e760cd91 100644 --- a/python/pyarrow-stubs/compute.pyi +++ b/python/pyarrow-stubs/compute.pyi @@ -257,9 +257,9 @@ _NumericOrTemporalScalar: TypeAlias = _NumericScalar | _TemporalScalar # the result is, e.g. a StringArray for a string input. _ArrayOrChunkedArray: TypeAlias = Array | ChunkedArray _ScalarOrArray: TypeAlias = Scalar | Array | ChunkedArray -_ArrayLike: TypeAlias = ( - list[Any] | tuple[Any, ...] | NDArray[Any] | Array | ChunkedArray -) +# Python values that compute functions convert to arrays. Other values are +# converted to scalars. +_ArrayLike: TypeAlias = list[Any] | tuple[Any, ...] | NDArray[Any] _ComputeInput: TypeAlias = _ScalarOrArray | _ArrayLike | Expression _DecimalArray: TypeAlias = ( Decimal32Array | Decimal64Array | Decimal128Array | Decimal256Array @@ -1102,24 +1102,25 @@ def case_when( memory_pool: MemoryPool | None = None, ) -> _ScalarOrArray | Array | Expression: ... def choose( - indices: _ArrayLike | ScalarLike | Expression, + indices: _ComputeInput | ScalarLike, /, - *values: _ArrayLike | ScalarLike, + *values: _ScalarOrArray | _ArrayLike | ScalarLike, memory_pool: MemoryPool | None = None, ) -> _ScalarOrArray | Expression: ... def coalesce( *values: _ScalarOrArray | Expression, memory_pool: MemoryPool | None = None ) -> _ScalarOrArray | Expression: ... def if_else( - cond: _ArrayLike | ScalarLike | Expression, - left: _ArrayLike | ScalarLike, - right: _ArrayLike | ScalarLike, + cond: _ComputeInput | ScalarLike, + left: _ScalarOrArray | _ArrayLike | ScalarLike, + right: _ScalarOrArray | _ArrayLike | ScalarLike, /, *, memory_pool: MemoryPool | None = None, ) -> _ScalarOrArray | Expression: ... def fill_null( - values: _ScalarOrArray | ScalarLike, fill_value: _ArrayLike | ScalarLike + values: _ScalarOrArray | ScalarLike, + fill_value: _ScalarOrArray | _ArrayLike | ScalarLike, ) -> _ScalarOrArray | ScalarLike: ... # ========================= Structural transforms ========================= @@ -1645,7 +1646,7 @@ def fill_null_forward( def replace_with_mask( values: _ScalarOrArray | Expression, mask: Mask, - replacements: _ArrayLike, + replacements: _ArrayOrChunkedArray | _ArrayLike, /, *, memory_pool: MemoryPool | None = None, From 46fcb301751045fcea46e5a8f229b0c0364cc7e4 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Sat, 21 Nov 2026 12:40:26 +0100 Subject: [PATCH 14/33] Replace ScalarLike, review comparison, logical and string stubs --- python/pyarrow-stubs-tests/test_compute.py | 57 +++++-- python/pyarrow-stubs/_stubs_typing.pyi | 1 - python/pyarrow-stubs/compute.pyi | 171 +++++++++++---------- 3 files changed, 139 insertions(+), 90 deletions(-) diff --git a/python/pyarrow-stubs-tests/test_compute.py b/python/pyarrow-stubs-tests/test_compute.py index 25325f3d2aa5..61f7b28cbbe0 100644 --- a/python/pyarrow-stubs-tests/test_compute.py +++ b/python/pyarrow-stubs-tests/test_compute.py @@ -15,6 +15,8 @@ # specific language governing permissions and limitations # under the License. +import datetime as dt + from collections.abc import Hashable from decimal import Decimal from types import EllipsisType @@ -193,7 +195,6 @@ def test_array_wise_functions() -> None: check(assert_type(pc.partition_nth_indices([3, 1, 2], pivot=1), pa.UInt64Array | pc.Expression), pa.UInt64Array) - taken = pc.take(arr, [0, 2]) check(assert_type(taken, pa.Array | pa.ChunkedArray | pa.RecordBatch | pa.Table), pa.Array) @@ -211,11 +212,12 @@ def test_array_wise_functions() -> None: def test_element_wise_functions() -> None: + import numpy as np arr = pa.array([3, 1, 2]) check(assert_type(pc.random(3), pa.DoubleArray), pa.DoubleArray) - # Arithmetic: Python literals, lists and tuples accepted + # Arithmetic: Python literals, lists and tuples check(pc.abs([1, 2]), pa.Int64Array) check(pc.abs((1.5, -2.5)), pa.DoubleArray) check(pc.abs(1), pa.Int64Scalar) @@ -230,6 +232,10 @@ def test_element_wise_functions() -> None: check(pc.modulo([7, -7], [3, 3]), pa.Int64Array) check(pc.power(arr, 2), pa.Array) check(pc.sqrt(pa.chunked_array([[1], [2, 3]])), pa.ChunkedArray) + # decimal, datetime and numpy also accepted + check(pc.sqrt(Decimal("2.25")), pa.DoubleScalar) + check(pc.add(dt.datetime(2026, 1, 1), dt.timedelta(days=1)), pa.TimestampScalar) + check(pc.add(arr, np.int64(1)), pa.Int64Array) # Bit-wise functions check(pc.bit_wise_and([1, 1], [1, 1]), pa.Int64Array) @@ -240,6 +246,8 @@ def test_element_wise_functions() -> None: check(pc.floor([1, 2]), pa.DoubleArray) check(pc.trunc(pa.scalar(Decimal("1.5"))), pa.Decimal128Scalar) check(pc.trunc(pa.array([Decimal("1.5")])), pa.Decimal128Array) + check(pc.round((1.5, 2.5)), pa.Array) + check(pc.round([1.5, 2.5]), pa.Array) # Logarithms return floats check(pc.ln(pa.array([Decimal("1.5")])), pa.DoubleArray) @@ -250,24 +258,48 @@ def test_element_wise_functions() -> None: check(pc.acos(0.5), pa.DoubleScalar) check(pc.atan2(1.5, [1, 2]), pa.DoubleArray) check(pc.cosh(pa.array([Decimal("1.5")])), pa.DoubleArray) - - # Python lists and tuples accepted - check(pc.round((1.5, 2.5)), pa.Array) - check(pc.round([1.5, 2.5]), pa.Array) - check(pc.binary_repeat(pa.array(["a"]), (2,)), pa.Array) - check(pc.binary_join_element_wise(["a", "b"], ["c", "d"], "-"), pa.Array) - check(pc.struct_field(pa.array([{"a": 1}]), ("a",)), pa.Array) check(pc.acos([1.1, 1.1]), pa.DoubleArray) check(pc.atan2([1.1, 1.1], [1.1, 1.1]), pa.DoubleArray) - # An Expression as the first argument gives an Expression + # Comparisons and selections accept Python literals of any type + check(pc.equal(pa.scalar("a"), "a"), pa.BooleanScalar) + check(pc.equal(True, False), pa.BooleanScalar) + check(pc.max_element_wise(pa.array(["a", "b"]), "c"), pa.StringArray) + check(pc.less(dt.datetime(2026, 1, 1), dt.datetime(2026, 1, 2)), pa.BooleanScalar) + check(pc.greater_equal(1.1, 2.2), pa.BooleanScalar) + check(pc.if_else(True, 1, 2), pa.Int64Scalar) selected = pc.if_else([True, False], [1, 2], [3, 4]) check(assert_type(selected, pa.Scalar | pa.Array | pa.ChunkedArray | pc.Expression), pa.Array) + check(pc.choose(1, [1, 2], [3, 4]), pa.Int64Array) + check(pc.fill_null(pa.array([1, None]), 5), pa.Int64Array) + check(pc.equal([1, 2, 1], [1, 2, 3]), pa.BooleanArray) + + # Logical functions + check(pc.and_not([True], [False]), pa.BooleanArray) + + # String functions + check(pc.utf8_is_space([" "]), pa.BooleanArray) + check(pc.binary_repeat(pa.array(["a"]), (2,)), pa.Array) + check(pc.binary_repeat(b"foozfoo", [3]), pa.BinaryArray) + check(pc.replace_substring(b"foozfoo", "foo", "bar"), pa.BinaryScalar) + check(pc.ascii_ltrim(["foozfoo"], b"foo"), pa.StringArray) + check(pc.split_pattern([b"foozfoo"], b"t"), pa.ListArray) + check(pc.extract_regex(b"a1", rb"(?P[ab])(?P\d)"), + pa.StructScalar) + check(pc.binary_join([["a", "b"], ["c"]], "-"), pa.StringArray) + check(pc.binary_join(pc.field("a"), pc.field("sep")), pc.Expression) + check(pc.binary_join_element_wise(["a", "b"], ["c", "d"], "-"), pa.Array) + + # Structural transforms + check(pc.struct_field(pa.array([{"a": 1}]), ("a",)), pa.Array) + + # An Expression as the first argument gives an Expression check(pc.if_else(pc.field("a") > 1, 1, 2), pc.Expression) # TODO: test invalid code once the scalar stubs are annotated # pc.bit_wise_and(1.0, 1.0), pc.bit_wise_not(1.0) + # pc.add("a", 1), pc.sqrt(dt.timedelta(days=1)), pc.if_else("yes", 1, 2) def test_agg_functions() -> None: @@ -281,7 +313,6 @@ def test_agg_functions() -> None: check(pc.count_distinct(scalar), pa.Int64Scalar) check(pc.first(scalar), pa.Int64Scalar) check(pc.last(scalar), pa.Int64Scalar) - check(pc.first_last((1, 2)), pa.StructScalar) check(pc.first_last(scalar), pa.StructScalar) # Quantile returns doubles, or the input type for "lower", "higher", "nearest" @@ -295,7 +326,11 @@ def test_agg_functions() -> None: check(pc.variance([1, 2, 3]), pa.DoubleScalar) check(pc.variance((1, 2, 3)), pa.DoubleScalar) check(pc.variance(np.array([1.0, 2.0, 3.0])), pa.DoubleScalar) + check(pc.first_last((1, 2)), pa.StructScalar) # An Expression as input gives an Expression check(pc.mean(arr), pa.DoubleScalar) check(pc.mean(pc.field(0)), pc.Expression) + + # A Python value accepted + check(pc.index(arr, 2), pa.Int64Scalar) diff --git a/python/pyarrow-stubs/_stubs_typing.pyi b/python/pyarrow-stubs/_stubs_typing.pyi index 0f9bcf887c55..17ee2cffc316 100644 --- a/python/pyarrow-stubs/_stubs_typing.pyi +++ b/python/pyarrow-stubs/_stubs_typing.pyi @@ -24,7 +24,6 @@ from pyarrow.lib import Array, ChunkedArray from pyarrow import lib -ScalarLike: TypeAlias = Any Order: TypeAlias = Literal["ascending", "descending"] MapsAsPydicts: TypeAlias = Literal["lossy", "strict"] NullEncoding: TypeAlias = Literal["mask", "encode"] diff --git a/python/pyarrow-stubs/compute.pyi b/python/pyarrow-stubs/compute.pyi index 7b14e760cd91..2c0baa7d050f 100644 --- a/python/pyarrow-stubs/compute.pyi +++ b/python/pyarrow-stubs/compute.pyi @@ -15,9 +15,13 @@ # specific language governing permissions and limitations # under the License. +import datetime as dt + from collections.abc import Callable, Hashable, Sequence +from decimal import Decimal from typing import Any, ParamSpec, TypeAlias, TypeVar +import numpy as np from numpy.typing import NDArray # Placeholders (Any) until scalar.pyi is annotated; mypy rejects them as @@ -164,7 +168,6 @@ from pyarrow._stubs_typing import ( NullPlacement, NullSelectionBehavior, Order, - ScalarLike, TimeUnit, ) from pyarrow.lib import ( @@ -261,6 +264,11 @@ _ScalarOrArray: TypeAlias = Scalar | Array | ChunkedArray # converted to scalars. _ArrayLike: TypeAlias = list[Any] | tuple[Any, ...] | NDArray[Any] _ComputeInput: TypeAlias = _ScalarOrArray | _ArrayLike | Expression +# Python literals that compute functions convert to scalars. An int is +# accepted where a float is. np.generic covers NumPy scalars. +_NumericLiteral: TypeAlias = float | Decimal | np.generic +_TemporalLiteral: TypeAlias = dt.date | dt.time | dt.timedelta | np.generic +_Literal: TypeAlias = _NumericLiteral | _TemporalLiteral | bool | str | bytes _DecimalArray: TypeAlias = ( Decimal32Array | Decimal64Array | Decimal128Array | Decimal256Array ) @@ -341,7 +349,7 @@ def first_last( ) -> StructScalar | Expression: ... def index( data: _ArrayOrChunkedArray, - value: ScalarLike, + value: Scalar | _Literal, start: int | None = None, end: int | None = None, *, @@ -470,7 +478,7 @@ def variance( # ========================= Arithmetic functions ========================= def abs( - x: _ComputeInput | float, + x: _ComputeInput | _NumericLiteral | _TemporalLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -479,8 +487,8 @@ def abs( abs_checked = _clone_signature(abs) def add( - x: _ComputeInput | float, - y: _ComputeInput | float, + x: _ComputeInput | _NumericLiteral | _TemporalLiteral, + y: _ComputeInput | _NumericLiteral | _TemporalLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -489,8 +497,8 @@ def add( add_checked = _clone_signature(add) def divide( - x: _ComputeInput | float, - y: _ComputeInput | float, + x: _ComputeInput | _NumericLiteral | _TemporalLiteral, + y: _ComputeInput | _NumericLiteral | _TemporalLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -499,7 +507,7 @@ def divide( divide_checked = _clone_signature(divide) def exp( - exponent: _ComputeInput | float, + exponent: _ComputeInput | _NumericLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -515,15 +523,15 @@ def exp( expm1 = _clone_signature(exp) def hypot( - x: _ComputeInput | float, - y: _ComputeInput | float, + x: _ComputeInput | _NumericLiteral, + y: _ComputeInput | _NumericLiteral, /, *, memory_pool: MemoryPool | None = None, ) -> _FloatScalar | FloatingPointArray | ChunkedArray | Expression: ... def modulo( - dividend: _ComputeInput | float, - divisor: _ComputeInput | float, + dividend: _ComputeInput | _NumericLiteral, + divisor: _ComputeInput | _NumericLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -534,7 +542,7 @@ multiply = _clone_signature(add) multiply_checked = _clone_signature(add) def negate( - x: _ComputeInput | float, + x: _ComputeInput | _NumericLiteral | _TemporalLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -543,8 +551,8 @@ def negate( negate_checked = _clone_signature(negate) def power( - base: _ComputeInput | float, - exponent: _ComputeInput | float, + base: _ComputeInput | _NumericLiteral, + exponent: _ComputeInput | _NumericLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -555,13 +563,13 @@ remainder = _clone_signature(modulo) remainder_checked = _clone_signature(modulo) def sign( - x: _ComputeInput | float, + x: _ComputeInput | _NumericLiteral | _TemporalLiteral, /, *, memory_pool: MemoryPool | None = None, ) -> Int8Scalar | _FloatScalar | NumericArray | ChunkedArray | Expression: ... def sqrt( - x: _ComputeInput | float, + x: _ComputeInput | _NumericLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -595,7 +603,7 @@ shift_right_checked = _clone_signature(bit_wise_and) # ========================= Rounding functions ========================= def ceil( - x: _ComputeInput | float, + x: _ComputeInput | _NumericLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -611,7 +619,7 @@ def ceil( floor = _clone_signature(ceil) def round( - x: _ComputeInput | float, + x: _ComputeInput | _NumericLiteral, /, ndigits: int = 0, round_mode: _RoundMode = "half_to_even", @@ -620,7 +628,7 @@ def round( memory_pool: MemoryPool | None = None, ) -> _NumericScalar | _NumericArray | ChunkedArray | Expression: ... def round_to_multiple( - x: _ComputeInput | float, + x: _ComputeInput | _NumericLiteral, /, multiple: float | Scalar = 1.0, round_mode: _RoundMode = "half_to_even", @@ -629,7 +637,7 @@ def round_to_multiple( memory_pool: MemoryPool | None = None, ) -> _NumericScalar | _NumericArray | ChunkedArray | Expression: ... def round_binary( - x: _ComputeInput | float, + x: _ComputeInput | _NumericLiteral, s: _ComputeInput | int, /, round_mode: _RoundMode = "half_to_even", @@ -642,7 +650,7 @@ trunc = _clone_signature(ceil) # ========================= Logarithmic functions ========================= def ln( - x: _ComputeInput | float, + x: _ComputeInput | _NumericLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -657,8 +665,8 @@ log2 = _clone_signature(ln) log2_checked = _clone_signature(ln) def logb( - x: _ComputeInput | float, - b: _ComputeInput | float, + x: _ComputeInput | _NumericLiteral, + b: _ComputeInput | _NumericLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -674,8 +682,8 @@ asin_checked = _clone_signature(ln) atan = _clone_signature(ln) def atan2( - y: _ComputeInput | float, - x: _ComputeInput | float, + y: _ComputeInput | _NumericLiteral, + x: _ComputeInput | _NumericLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -700,8 +708,8 @@ tanh = _clone_signature(ln) # ========================= Comparisons ========================= def equal( - x: _ScalarOrArray | ScalarLike | Expression, - y: _ScalarOrArray | ScalarLike | Expression, + x: _ComputeInput | _Literal, + y: _ComputeInput | _Literal, /, *, memory_pool: MemoryPool | None = None, @@ -714,18 +722,25 @@ less_equal = _clone_signature(equal) not_equal = _clone_signature(equal) def max_element_wise( - *args: _ScalarOrArray | Expression | ScalarLike | _ArrayLike, + *args: _ComputeInput | _Literal, skip_nulls: bool = True, options: ElementWiseAggregateOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _ScalarOrArray | Expression: ... +) -> ( + _NumericOrTemporalScalar + | _StringOrBinaryScalar + | _NumericOrTemporalArray + | _StringOrBinaryArray + | ChunkedArray + | Expression +): ... min_element_wise = _clone_signature(max_element_wise) # ========================= Logical functions ========================= def and_( - x: _ScalarOrArray | bool | Expression, - y: _ScalarOrArray | bool | Expression, + x: _ComputeInput | bool, + y: _ComputeInput | bool, /, *, memory_pool: MemoryPool | None = None, @@ -736,7 +751,7 @@ and_not = _clone_signature(and_) and_not_kleene = _clone_signature(and_) def invert( - x: _ScalarOrArray | Expression, + x: _ComputeInput | bool, /, *, memory_pool: MemoryPool | None = None, @@ -748,7 +763,7 @@ xor = _clone_signature(and_) # ========================= String predicates ========================= def ascii_is_alnum( - strings: _ScalarOrArray | Expression, + strings: _ComputeInput | str, /, *, memory_pool: MemoryPool | None = None, @@ -775,7 +790,7 @@ string_is_ascii = _clone_signature(ascii_is_alnum) # ========================= String transforms ========================= def ascii_capitalize( - strings: _ScalarOrArray | Expression, + strings: _ComputeInput | str, /, *, memory_pool: MemoryPool | None = None, @@ -788,7 +803,7 @@ ascii_title = _clone_signature(ascii_capitalize) ascii_upper = _clone_signature(ascii_capitalize) def binary_length( - strings: _ScalarOrArray | Expression, + strings: _ComputeInput | str | bytes, /, *, memory_pool: MemoryPool | None = None, @@ -796,14 +811,14 @@ def binary_length( Int32Scalar | Int64Scalar | Int32Array | Int64Array | ChunkedArray | Expression ): ... def binary_repeat( - strings: _ScalarOrArray | Expression, - num_repeats: int | _ComputeInput, + strings: _ComputeInput | str | bytes, + num_repeats: _ComputeInput | int, /, *, memory_pool: MemoryPool | None = None, ) -> _StringOrBinaryScalar | _StringOrBinaryArray | ChunkedArray | Expression: ... def binary_replace_slice( - strings: _ScalarOrArray | Expression, + strings: _ComputeInput | str | bytes, /, start: int, stop: int, @@ -813,13 +828,13 @@ def binary_replace_slice( memory_pool: MemoryPool | None = None, ) -> _StringOrBinaryScalar | _StringOrBinaryArray | ChunkedArray | Expression: ... def binary_reverse( - strings: _ScalarOrArray | Expression, + strings: _ComputeInput | bytes, /, *, memory_pool: MemoryPool | None = None, ) -> _BinaryScalar | _BinaryArray | ChunkedArray | Expression: ... def replace_substring( - strings: _ScalarOrArray | Expression, + strings: _ComputeInput | str | bytes, /, pattern: str | bytes, replacement: str | bytes, @@ -827,18 +842,18 @@ def replace_substring( max_replacements: int | None = None, options: ReplaceSubstringOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _StringScalar | _StringArray | ChunkedArray | Expression: ... +) -> _StringOrBinaryScalar | _StringOrBinaryArray | ChunkedArray | Expression: ... replace_substring_regex = _clone_signature(replace_substring) def utf8_capitalize( - strings: _ScalarOrArray | Expression, + strings: _ComputeInput | str, /, *, memory_pool: MemoryPool | None = None, ) -> _StringScalar | _StringArray | ChunkedArray | Expression: ... def utf8_length( - strings: _ScalarOrArray | Expression, + strings: _ComputeInput | str, /, *, memory_pool: MemoryPool | None = None, @@ -849,7 +864,7 @@ def utf8_length( utf8_lower = _clone_signature(utf8_capitalize) def utf8_replace_slice( - strings: _ScalarOrArray | Expression, + strings: _ComputeInput | str, /, start: int, stop: int, @@ -865,7 +880,7 @@ utf8_title = _clone_signature(utf8_capitalize) utf8_upper = _clone_signature(utf8_capitalize) def utf8_normalize( - strings: _ScalarOrArray | Expression, + strings: _ComputeInput | str, /, form: _Form, *, @@ -875,7 +890,7 @@ def utf8_normalize( # ========================= String padding ========================= def ascii_center( - strings: _ScalarOrArray | Expression, + strings: _ComputeInput | str, /, width: int, padding: str = " ", @@ -892,7 +907,7 @@ utf8_lpad = _clone_signature(ascii_center) utf8_rpad = _clone_signature(ascii_center) def utf8_zero_fill( - strings: _ScalarOrArray | Expression, + strings: _ComputeInput | str, /, width: int, padding: str = "0", @@ -905,15 +920,15 @@ utf8_zfill = utf8_zero_fill # ========================= String trimming ========================= def ascii_ltrim( - strings: _ScalarOrArray | Expression, + strings: _ComputeInput | str, /, - characters: str, + characters: str | bytes, *, options: TrimOptions | None = None, memory_pool: MemoryPool | None = None, ) -> _StringScalar | _StringArray | ChunkedArray | Expression: ... def ascii_ltrim_whitespace( - strings: _ScalarOrArray | Expression, + strings: _ComputeInput | str, /, *, memory_pool: MemoryPool | None = None, @@ -932,7 +947,7 @@ utf8_trim_whitespace = _clone_signature(ascii_ltrim_whitespace) # ========================= String splitting ========================= def ascii_split_whitespace( - strings: _ScalarOrArray | Expression, + strings: _ComputeInput | str | bytes, /, *, max_splits: int | None = None, @@ -941,9 +956,9 @@ def ascii_split_whitespace( memory_pool: MemoryPool | None = None, ) -> _ListScalar | BaseListArray | ChunkedArray | Expression: ... def split_pattern( - strings: _ScalarOrArray | Expression, + strings: _ComputeInput | str, /, - pattern: str, + pattern: str | bytes, *, max_splits: int | None = None, reverse: bool = False, @@ -956,9 +971,9 @@ utf8_split_whitespace = _clone_signature(ascii_split_whitespace) # ========================= String component extraction ========================= def extract_regex( - strings: _ScalarOrArray | Expression, + strings: _ComputeInput | str | bytes, /, - pattern: str, + pattern: str | bytes, *, options: ExtractRegexOptions | None = None, memory_pool: MemoryPool | None = None, @@ -968,14 +983,14 @@ extract_regex_span = _clone_signature(extract_regex) # ========================= String joining ========================= def binary_join( - strings: _ScalarOrArray | Expression, - separator: str | bytes | _ScalarOrArray | Expression, + strings: _ComputeInput, + separator: _ComputeInput | str | bytes, /, *, memory_pool: MemoryPool | None = None, ) -> _StringOrBinaryScalar | _StringOrBinaryArray | ChunkedArray | Expression: ... def binary_join_element_wise( - *strings: str | bytes | _ComputeInput, + *strings: _ComputeInput | str | bytes, null_handling: _NullHandling = "emit_null", null_replacement: str = "", options: JoinOptions | None = None, @@ -984,7 +999,7 @@ def binary_join_element_wise( # ========================= String Slicing ========================= def binary_slice( - strings: _ScalarOrArray | Expression, + strings: _ComputeInput | bytes, /, start: int, stop: int | None = None, @@ -994,7 +1009,7 @@ def binary_slice( memory_pool: MemoryPool | None = None, ) -> _BinaryScalar | _BinaryArray | ChunkedArray | Expression: ... def utf8_slice_codeunits( - strings: _ScalarOrArray | Expression, + strings: _ComputeInput | str, /, start: int, stop: int | None = None, @@ -1086,7 +1101,7 @@ def is_null( memory_pool: MemoryPool | None = None, ) -> BooleanScalar | BooleanArray | ChunkedArray | Expression: ... def is_valid( - values: _ScalarOrArray | Expression | _ArrayLike, + values: _ScalarOrArray | _ArrayLike | Expression, /, *, memory_pool: MemoryPool | None = None, @@ -1102,26 +1117,26 @@ def case_when( memory_pool: MemoryPool | None = None, ) -> _ScalarOrArray | Array | Expression: ... def choose( - indices: _ComputeInput | ScalarLike, + indices: _ComputeInput | int, /, - *values: _ScalarOrArray | _ArrayLike | ScalarLike, + *values: _ScalarOrArray | _ArrayLike | _Literal, memory_pool: MemoryPool | None = None, ) -> _ScalarOrArray | Expression: ... def coalesce( *values: _ScalarOrArray | Expression, memory_pool: MemoryPool | None = None ) -> _ScalarOrArray | Expression: ... def if_else( - cond: _ComputeInput | ScalarLike, - left: _ScalarOrArray | _ArrayLike | ScalarLike, - right: _ScalarOrArray | _ArrayLike | ScalarLike, + cond: _ComputeInput | bool | np.generic, + left: _ScalarOrArray | _ArrayLike | _Literal, + right: _ScalarOrArray | _ArrayLike | _Literal, /, *, memory_pool: MemoryPool | None = None, ) -> _ScalarOrArray | Expression: ... def fill_null( - values: _ScalarOrArray | ScalarLike, - fill_value: _ScalarOrArray | _ArrayLike | ScalarLike, -) -> _ScalarOrArray | ScalarLike: ... + values: _ScalarOrArray, + fill_value: _ScalarOrArray | _Literal, +) -> _ScalarOrArray: ... # ========================= Structural transforms ========================= def list_value_length( @@ -1133,7 +1148,7 @@ def list_value_length( Int32Scalar | Int64Scalar | Int32Array | Int64Array | ChunkedArray | Expression ): ... def make_struct( - *args: _ScalarOrArray | Expression | _ArrayLike, + *args: _ScalarOrArray | _ArrayLike | Expression, field_names: Sequence[str] = (), field_nullability: bool | None = None, field_metadata: Sequence[KeyValueMetadata] | None = None, @@ -1555,7 +1570,7 @@ def sort_indices( ) -> UInt64Array | Expression: ... def search_sorted( values: _ArrayOrChunkedArray | Expression, - needles: _ScalarOrArray | ScalarLike | Expression, + needles: _ScalarOrArray | _Literal | Expression, /, side: _Side = "left", *, @@ -1615,7 +1630,7 @@ def list_slice( def map_lookup( container: _ScalarOrArray | Expression, /, - query_key: ScalarLike, + query_key: Scalar | _Literal, occurrence: _Occurrence, *, options: MapLookupOptions | None = None, @@ -1624,7 +1639,7 @@ def map_lookup( def struct_field( values: _ScalarOrArray | Expression, /, - indices: Sequence[str | bytes | int] | Expression | bytes | str | int, + indices: Sequence[str | bytes | int] | bytes | str | int | Expression, *, options: StructFieldOptions | None = None, memory_pool: MemoryPool | None = None, @@ -1632,17 +1647,17 @@ def struct_field( # ========================= Replace functions ========================= def fill_null_backward( - values: _ScalarOrArray | ScalarLike | Expression, + values: _ScalarOrArray | _Literal | Expression, /, *, memory_pool: MemoryPool | None = None, -) -> _ScalarOrArray | ScalarLike | Expression: ... +) -> _ScalarOrArray | Expression: ... def fill_null_forward( - values: _ScalarOrArray | ScalarLike | Expression, + values: _ScalarOrArray | _Literal | Expression, /, *, memory_pool: MemoryPool | None = None, -) -> _ScalarOrArray | ScalarLike | Expression: ... +) -> _ScalarOrArray | Expression: ... def replace_with_mask( values: _ScalarOrArray | Expression, mask: Mask, From e78c2a5c4cd6c686225fdc6d389d25662e9ce636 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Mon, 23 Nov 2026 07:52:27 +0100 Subject: [PATCH 15/33] Review containment tests functions --- python/pyarrow-stubs-tests/test_compute.py | 19 +++++++++++--- python/pyarrow-stubs/_compute.pyi | 2 +- python/pyarrow-stubs/compute.pyi | 29 +++++++++++++--------- python/pyarrow/_compute.pyx | 2 +- 4 files changed, 35 insertions(+), 17 deletions(-) diff --git a/python/pyarrow-stubs-tests/test_compute.py b/python/pyarrow-stubs-tests/test_compute.py index 61f7b28cbbe0..d8bcb918cb7e 100644 --- a/python/pyarrow-stubs-tests/test_compute.py +++ b/python/pyarrow-stubs-tests/test_compute.py @@ -157,6 +157,8 @@ def test_options() -> None: if TYPE_CHECKING: pc.RoundOptions(2, round_mode="nearest") # type: ignore[arg-type] + # TODO: test invalid code once the scalar stubs are annotated + # pc.SetLookupOptions(pa.scalar(2)) pc.SearchSortedOptions(side="middle") # type: ignore[arg-type] _: Hashable = options # type: ignore[assignment] # ty: ignore[invalid-assignment] # noqa: E501 @@ -291,15 +293,26 @@ def test_element_wise_functions() -> None: check(pc.binary_join(pc.field("a"), pc.field("sep")), pc.Expression) check(pc.binary_join_element_wise(["a", "b"], ["c", "d"], "-"), pa.Array) + # Containment tests + check(pc.count_substring([b"abcab"], "ab"), pa.Int32Array) + check(pc.ends_with([b"abcab"], "ab"), pa.BooleanArray) + check(pc.index_in([1, 2, 3], pa.array([1, 2])), pa.Int32Array) + check(pc.is_in([1, 2, 3], pa.array([1, 2])), pa.BooleanArray) + check(pc.index_in_meta_binary([1, 2, 3], [1, 2]), pa.Int32Array) + check(pc.is_in_meta_binary([1, 2, 3], [1, 2]), pa.BooleanArray) + # Structural transforms check(pc.struct_field(pa.array([{"a": 1}]), ("a",)), pa.Array) # An Expression as the first argument gives an Expression check(pc.if_else(pc.field("a") > 1, 1, 2), pc.Expression) - # TODO: test invalid code once the scalar stubs are annotated - # pc.bit_wise_and(1.0, 1.0), pc.bit_wise_not(1.0) - # pc.add("a", 1), pc.sqrt(dt.timedelta(days=1)), pc.if_else("yes", 1, 2) + if TYPE_CHECKING: + pc.is_in([1, 2, 3], pc.field("a")) # type: ignore[arg-type] + # TODO: test invalid code once the scalar stubs are annotated + # pc.bit_wise_and(1.0, 1.0), pc.bit_wise_not(1.0) + # pc.add("a", 1), pc.sqrt(dt.timedelta(days=1)), pc.if_else("yes", 1, 2) + # pc.index_in([1, 2, 3], options=pc.SetLookupOptions(pa.scalar(2))) def test_agg_functions() -> None: diff --git a/python/pyarrow-stubs/_compute.pyi b/python/pyarrow-stubs/_compute.pyi index c756b4c59dcb..15d37174cef5 100644 --- a/python/pyarrow-stubs/_compute.pyi +++ b/python/pyarrow-stubs/_compute.pyi @@ -310,7 +310,7 @@ class ModeOptions(FunctionOptions): class SetLookupOptions(FunctionOptions): def __init__( - self, value_set: Array | ChunkedArray | Scalar, *, skip_nulls: bool = False + self, value_set: Array | ChunkedArray, *, skip_nulls: bool = False ) -> None: ... class StrptimeOptions(FunctionOptions): diff --git a/python/pyarrow-stubs/compute.pyi b/python/pyarrow-stubs/compute.pyi index 2c0baa7d050f..bed3fe901a60 100644 --- a/python/pyarrow-stubs/compute.pyi +++ b/python/pyarrow-stubs/compute.pyi @@ -1021,9 +1021,9 @@ def utf8_slice_codeunits( # ========================= Containment tests ========================= def count_substring( - strings: _ScalarOrArray | Expression, + strings: _ComputeInput | str | bytes, /, - pattern: str, + pattern: str | bytes, *, ignore_case: bool = False, options: MatchSubstringOptions | None = None, @@ -1035,9 +1035,9 @@ def count_substring( count_substring_regex = _clone_signature(count_substring) def ends_with( - strings: _ScalarOrArray | Expression, + strings: _ComputeInput | str | bytes, /, - pattern: str, + pattern: str | bytes, *, ignore_case: bool = False, options: MatchSubstringOptions | None = None, @@ -1048,18 +1048,18 @@ find_substring = _clone_signature(count_substring) find_substring_regex = _clone_signature(count_substring) def index_in( - values: _ScalarOrArray | Expression, + values: _ComputeInput, /, - value_set: _ArrayOrChunkedArray | Expression, + value_set: _ArrayOrChunkedArray, *, skip_nulls: bool = False, options: SetLookupOptions | None = None, memory_pool: MemoryPool | None = None, ) -> Int32Scalar | Int32Array | ChunkedArray | Expression: ... def is_in( - values: _ScalarOrArray | Expression, + values: _ComputeInput, /, - value_set: _ArrayOrChunkedArray | Expression, + value_set: _ArrayOrChunkedArray, *, skip_nulls: bool = False, options: SetLookupOptions | None = None, @@ -1072,14 +1072,19 @@ match_substring_regex = _clone_signature(ends_with) starts_with = _clone_signature(ends_with) def index_in_meta_binary( - values: _ScalarOrArray | Expression, - value_set: _ArrayOrChunkedArray | Expression, + values: _ArrayOrChunkedArray | _ArrayLike, + value_set: _ArrayOrChunkedArray | _ArrayLike, /, *, memory_pool: MemoryPool | None = None, ) -> Int32Scalar | Int32Array | ChunkedArray | Expression: ... - -is_in_meta_binary = _clone_signature(index_in_meta_binary) +def is_in_meta_binary( + values: _ArrayOrChunkedArray | _ArrayLike, + value_set: _ArrayOrChunkedArray | _ArrayLike, + /, + *, + memory_pool: MemoryPool | None = None, +) -> BooleanScalar | BooleanArray | ChunkedArray | Expression: ... # ========================= Categorizations ========================= def is_finite( diff --git a/python/pyarrow/_compute.pyx b/python/pyarrow/_compute.pyx index 5290b87730e7..d3eeb0688a52 100644 --- a/python/pyarrow/_compute.pyx +++ b/python/pyarrow/_compute.pyx @@ -1770,7 +1770,7 @@ class SetLookupOptions(_SetLookupOptions): Parameters ---------- - value_set : Array, ChunkedArray or Scalar + value_set : Array or ChunkedArray Set of values to look for in the input. skip_nulls : bool, default False If False, nulls in the input are matched in the value_set just From 0eddd2199bff66fa66ba3cf47641c45c2f43b03f Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Mon, 23 Nov 2026 08:30:22 +0100 Subject: [PATCH 16/33] Remove Expression from aggregation and meta function stubs --- python/pyarrow-stubs-tests/test_compute.py | 20 +++---- python/pyarrow-stubs/compute.pyi | 69 +++++++++++----------- 2 files changed, 45 insertions(+), 44 deletions(-) diff --git a/python/pyarrow-stubs-tests/test_compute.py b/python/pyarrow-stubs-tests/test_compute.py index d8bcb918cb7e..9cb9b6637b40 100644 --- a/python/pyarrow-stubs-tests/test_compute.py +++ b/python/pyarrow-stubs-tests/test_compute.py @@ -38,7 +38,6 @@ | pa.Decimal64Array | pa.Decimal128Array | pa.Decimal256Array - | pc.Expression ) @@ -66,9 +65,9 @@ def test_expression() -> None: pc.Expression) check(assert_type(field.equals(pc.field("a")), bool), bool) - # Compute functions on an expression build an expression - check(pc.count(field), pc.Expression) - check(pc.mean(field), pc.Expression) + # Element-wise compute functions on an expression build an expression + check(pc.abs(field), pc.Expression) + check(pc.utf8_upper(field), pc.Expression) if TYPE_CHECKING: # Expressions define __eq__ and are unhashable. @@ -332,8 +331,9 @@ def test_agg_functions() -> None: check(assert_type(pc.quantile(arr, q=[0.25, 0.75]), _Quantile), pa.DoubleArray) check(assert_type(pc.quantile(arr, interpolation="lower"), _Quantile), pa.Int64Array) - check(assert_type(pc.mode(arr, n=2), pa.StructArray | pc.Expression), - pa.StructArray) + + check(assert_type(pc.mode(arr, n=2), pa.StructArray), pa.StructArray) + check(pc.mean(arr), pa.DoubleScalar) # Python lists, tuples and NumPy arrays accepted check(pc.variance([1, 2, 3]), pa.DoubleScalar) @@ -341,9 +341,9 @@ def test_agg_functions() -> None: check(pc.variance(np.array([1.0, 2.0, 3.0])), pa.DoubleScalar) check(pc.first_last((1, 2)), pa.StructScalar) - # An Expression as input gives an Expression - check(pc.mean(arr), pa.DoubleScalar) - check(pc.mean(pc.field(0)), pc.Expression) - # A Python value accepted check(pc.index(arr, 2), pa.Int64Scalar) + + # TODO: test invalid code once the scalar stubs are annotated + # Aggregations can't be evaluated as expressions + # ds.dataset(table).to_table(columns={"total": pc.sum(pc.field("a"))}) diff --git a/python/pyarrow-stubs/compute.pyi b/python/pyarrow-stubs/compute.pyi index bed3fe901a60..77707c03a805 100644 --- a/python/pyarrow-stubs/compute.pyi +++ b/python/pyarrow-stubs/compute.pyi @@ -263,6 +263,7 @@ _ScalarOrArray: TypeAlias = Scalar | Array | ChunkedArray # Python values that compute functions convert to arrays. Other values are # converted to scalars. _ArrayLike: TypeAlias = list[Any] | tuple[Any, ...] | NDArray[Any] +# element-wise compute input (expressions only work with element-wise functions) _ComputeInput: TypeAlias = _ScalarOrArray | _ArrayLike | Expression # Python literals that compute functions convert to scalars. An int is # accepted where a float is. np.generic covers NumPy scalars. @@ -293,60 +294,60 @@ _TemporalArray: TypeAlias = ( # =============================== Aggregations ======================================== def all( - array: _ScalarOrArray | Expression, + array: _ScalarOrArray, /, *, skip_nulls: bool = True, min_count: int = 1, options: ScalarAggregateOptions | None = None, memory_pool: MemoryPool | None = None, -) -> BooleanScalar | Expression: ... +) -> BooleanScalar: ... any = _clone_signature(all) def approximate_median( - array: _ScalarOrArray | Expression, + array: _ScalarOrArray, /, *, skip_nulls: bool = True, min_count: int = 1, options: ScalarAggregateOptions | None = None, memory_pool: MemoryPool | None = None, -) -> DoubleScalar | Expression: ... +) -> DoubleScalar: ... def count( - array: _ScalarOrArray | Expression, + array: _ScalarOrArray, /, mode: _CountMode = "only_valid", *, options: CountOptions | None = None, memory_pool: MemoryPool | None = None, -) -> Int64Scalar | Expression: ... +) -> Int64Scalar: ... def count_distinct( - array: _ScalarOrArray | Expression, + array: _ScalarOrArray, /, mode: _CountMode = "only_valid", *, options: CountOptions | None = None, memory_pool: MemoryPool | None = None, -) -> Int64Scalar | Expression: ... +) -> Int64Scalar: ... def first( - array: _ScalarOrArray | Expression, + array: _ScalarOrArray, /, *, skip_nulls: bool = True, min_count: int = 1, options: ScalarAggregateOptions | None = None, memory_pool: MemoryPool | None = None, -) -> Scalar | Expression: ... +) -> Scalar: ... def first_last( - array: _ComputeInput, + array: _ScalarOrArray | _ArrayLike, /, *, skip_nulls: bool = True, min_count: int = 1, options: ScalarAggregateOptions | None = None, memory_pool: MemoryPool | None = None, -) -> StructScalar | Expression: ... +) -> StructScalar: ... def index( data: _ArrayOrChunkedArray, value: Scalar | _Literal, @@ -356,7 +357,7 @@ def index( memory_pool: MemoryPool | None = None, ) -> Int64Scalar: ... def kurtosis( - array: _ScalarOrArray | _ArrayLike | Expression, + array: _ScalarOrArray | _ArrayLike, /, *, skip_nulls: bool = True, @@ -364,26 +365,26 @@ def kurtosis( min_count: int = 0, options: SkewOptions | None = None, memory_pool: MemoryPool | None = None, -) -> DoubleScalar | Expression: ... +) -> DoubleScalar: ... last = _clone_signature(first) max = _clone_signature(first) def mean( - array: _ScalarOrArray | Expression, + array: _ScalarOrArray, /, *, skip_nulls: bool = True, min_count: int = 1, options: ScalarAggregateOptions | None = None, memory_pool: MemoryPool | None = None, -) -> DoubleScalar | _DecimalScalar | Expression: ... +) -> DoubleScalar | _DecimalScalar: ... min = _clone_signature(first) min_max = _clone_signature(first_last) def mode( - array: _ScalarOrArray | Expression, + array: _ScalarOrArray, /, n: int = 1, *, @@ -391,7 +392,7 @@ def mode( min_count: int = 0, options: ModeOptions | None = None, memory_pool: MemoryPool | None = None, -) -> StructArray | Expression: ... +) -> StructArray: ... def pivot_wider( pivot_keys: _ArrayOrChunkedArray | Sequence[str], pivot_values: _ArrayOrChunkedArray | Sequence[Any], @@ -403,16 +404,16 @@ def pivot_wider( memory_pool: MemoryPool | None = None, ) -> StructScalar: ... def product( - array: _ScalarOrArray | Expression, + array: _ScalarOrArray, /, *, skip_nulls: bool = True, min_count: int = 1, options: ScalarAggregateOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _NumericScalar | Expression: ... +) -> _NumericScalar: ... def quantile( - array: _ScalarOrArray | Expression, + array: _ScalarOrArray, /, q: float | Sequence[float] = 0.5, *, @@ -421,9 +422,9 @@ def quantile( min_count: int = 0, options: QuantileOptions | None = None, memory_pool: MemoryPool | None = None, -) -> NumericArray | _DecimalArray | Expression: ... +) -> NumericArray | _DecimalArray: ... def skew( - array: _ScalarOrArray | _ArrayLike | Expression, + array: _ScalarOrArray | _ArrayLike, /, *, skip_nulls: bool = True, @@ -431,9 +432,9 @@ def skew( min_count: int = 0, options: SkewOptions | None = None, memory_pool: MemoryPool | None = None, -) -> DoubleScalar | Expression: ... +) -> DoubleScalar: ... def stddev( - array: _ScalarOrArray | Expression, + array: _ScalarOrArray, /, *, ddof: float = 0, @@ -441,18 +442,18 @@ def stddev( min_count: int = 0, options: VarianceOptions | None = None, memory_pool: MemoryPool | None = None, -) -> DoubleScalar | Expression: ... +) -> DoubleScalar: ... def sum( - array: _ScalarOrArray | Expression, + array: _ScalarOrArray, /, *, skip_nulls: bool = True, min_count: int = 1, options: ScalarAggregateOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _NumericScalar | Expression: ... +) -> _NumericScalar: ... def tdigest( - array: _ScalarOrArray | Expression, + array: _ScalarOrArray, /, q: float | Sequence[float] = 0.5, *, @@ -462,9 +463,9 @@ def tdigest( min_count: int = 0, options: TDigestOptions | None = None, memory_pool: MemoryPool | None = None, -) -> DoubleArray | Expression: ... +) -> DoubleArray: ... def variance( - array: _ScalarOrArray | _ArrayLike | Expression, + array: _ScalarOrArray | _ArrayLike, /, *, ddof: int = 0, @@ -472,7 +473,7 @@ def variance( min_count: int = 0, options: VarianceOptions | None = None, memory_pool: MemoryPool | None = None, -) -> DoubleScalar | Expression: ... +) -> DoubleScalar: ... # =============================== Element-wise ("scalar") functions =================== @@ -1077,14 +1078,14 @@ def index_in_meta_binary( /, *, memory_pool: MemoryPool | None = None, -) -> Int32Scalar | Int32Array | ChunkedArray | Expression: ... +) -> Int32Scalar | Int32Array | ChunkedArray: ... def is_in_meta_binary( values: _ArrayOrChunkedArray | _ArrayLike, value_set: _ArrayOrChunkedArray | _ArrayLike, /, *, memory_pool: MemoryPool | None = None, -) -> BooleanScalar | BooleanArray | ChunkedArray | Expression: ... +) -> BooleanScalar | BooleanArray | ChunkedArray: ... # ========================= Categorizations ========================= def is_finite( From 166639c273c7afed01ca3e3a3d9e9f9a509a6688 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Mon, 23 Nov 2026 10:45:21 +0100 Subject: [PATCH 17/33] Review element-wise functions: categorization, selection, transforms and conversions --- python/pyarrow-stubs-tests/test_compute.py | 61 +++++++++++++++++----- python/pyarrow-stubs/compute.pyi | 46 ++++++++-------- 2 files changed, 71 insertions(+), 36 deletions(-) diff --git a/python/pyarrow-stubs-tests/test_compute.py b/python/pyarrow-stubs-tests/test_compute.py index 9cb9b6637b40..9eda3b8a5e86 100644 --- a/python/pyarrow-stubs-tests/test_compute.py +++ b/python/pyarrow-stubs-tests/test_compute.py @@ -88,9 +88,12 @@ class Message: def SerializeToString(self) -> bytes: return bytes(message) - check(pc.Expression.from_substrait(bytes(message)), pc.Expression) - check(pc.Expression.from_substrait(pa.py_buffer(message)), pc.Expression) - check(pc.Expression.from_substrait(Message()), pc.Expression) + check(assert_type(pc.Expression.from_substrait(bytes(message)), pc.Expression), + pc.Expression) + from_buffer = pc.Expression.from_substrait(pa.py_buffer(message)) + check(assert_type(from_buffer, pc.Expression), pc.Expression) + check(assert_type(pc.Expression.from_substrait(Message()), pc.Expression), + pc.Expression) def test_functions() -> None: @@ -200,6 +203,9 @@ def test_array_wise_functions() -> None: check(assert_type(taken, pa.Array | pa.ChunkedArray | pa.RecordBatch | pa.Table), pa.Array) + # Structural transforms + check(pc.struct_field(pa.array([{"a": 1}]), ("a",)), pa.Array) + # Replacements as an array or a Python list check(pc.replace_with_mask(arr, mask, pa.array([10, 30])), pa.Int64Array) check(pc.replace_with_mask(arr, mask, [10, 30]), pa.Int64Array) @@ -218,7 +224,7 @@ def test_element_wise_functions() -> None: check(assert_type(pc.random(3), pa.DoubleArray), pa.DoubleArray) - # Arithmetic: Python literals, lists and tuples + # Python literals, lists and tuples accepted check(pc.abs([1, 2]), pa.Int64Array) check(pc.abs((1.5, -2.5)), pa.DoubleArray) check(pc.abs(1), pa.Int64Scalar) @@ -233,6 +239,9 @@ def test_element_wise_functions() -> None: check(pc.modulo([7, -7], [3, 3]), pa.Int64Array) check(pc.power(arr, 2), pa.Array) check(pc.sqrt(pa.chunked_array([[1], [2, 3]])), pa.ChunkedArray) + check(pc.is_valid([1.1]), pa.BooleanArray) + check(pc.true_unless_null(1.1), pa.BooleanScalar) + # decimal, datetime and numpy also accepted check(pc.sqrt(Decimal("2.25")), pa.DoubleScalar) check(pc.add(dt.datetime(2026, 1, 1), dt.timedelta(days=1)), pa.TimestampScalar) @@ -272,10 +281,22 @@ def test_element_wise_functions() -> None: selected = pc.if_else([True, False], [1, 2], [3, 4]) check(assert_type(selected, pa.Scalar | pa.Array | pa.ChunkedArray | pc.Expression), pa.Array) + # An Expression as the first argument gives an Expression + check(pc.if_else(pc.field("a") > 1, 1, 2), pc.Expression) + check(pc.if_else(np.bool_(True), 1, 2), pa.Int64Scalar) check(pc.choose(1, [1, 2], [3, 4]), pa.Int64Array) check(pc.fill_null(pa.array([1, None]), 5), pa.Int64Array) check(pc.equal([1, 2, 1], [1, 2, 3]), pa.BooleanArray) + cond = pc.make_struct([True, False], [False, None]) + check(pc.case_when(cond, [1, 2], [12, 13]), pa.Int64Array) + cond = pa.scalar({"a": False, "b": True}) + check(pc.case_when(cond, ["foo"], ["bar"]), pa.StringArray) + check(pc.case_when(cond, 1, 2), pa.Int64Scalar) + check(pc.case_when(cond, "a", "b"), pa.StringScalar) + check(pc.case_when([{"a": True, "b": False}], [1.1], [3.3]), pa.DoubleArray) + check(pc.choose([1, 2, 1], "a", "b", "c"), pa.StringArray) + # Logical functions check(pc.and_not([True], [False]), pa.BooleanArray) @@ -301,17 +322,30 @@ def test_element_wise_functions() -> None: check(pc.is_in_meta_binary([1, 2, 3], [1, 2]), pa.BooleanArray) # Structural transforms - check(pc.struct_field(pa.array([{"a": 1}]), ("a",)), pa.Array) - - # An Expression as the first argument gives an Expression - check(pc.if_else(pc.field("a") > 1, 1, 2), pc.Expression) + check(pc.list_value_length([[1], [1, 2]]), pa.Int32Array) + + # Conversions + check(pc.ceil_temporal([dt.datetime(2026, 11, 23, 10, 17)]), pa.TimestampArray) + check(pc.cast(1, pa.float32()), pa.FloatScalar) + check(pc.strftime(dt.datetime(2026, 11, 23), format="%Y-%m-%d"), pa.StringScalar) + check(pc.strftime(pc.field("ts"), format=b"%Y-%m-%d"), pc.Expression) + check(pc.strptime(["5/1/2020", None, "12/13/1900"], format='%m/%d/%Y', unit='s'), + pa.TimestampArray) + check(pc.strptime("5/1/2020", format=b'%m/%d/%Y', unit='s'), pa.TimestampScalar) + ree = pc.run_end_encode([1, 1, None, None, None, 2, 2, 3]) + check(assert_type(ree, pa.RunEndEncodedArray | pa.ChunkedArray), + pa.RunEndEncodedArray) + check(assert_type(pc.run_end_decode(ree), pa.Array | pa.ChunkedArray), pa.Array) if TYPE_CHECKING: pc.is_in([1, 2, 3], pc.field("a")) # type: ignore[arg-type] + # Fails when evaluated (ds.dataset(table).to_table(columns={"r": ...})): + pc.run_end_encode(pc.field("a")) # type: ignore[arg-type] # TODO: test invalid code once the scalar stubs are annotated # pc.bit_wise_and(1.0, 1.0), pc.bit_wise_not(1.0) # pc.add("a", 1), pc.sqrt(dt.timedelta(days=1)), pc.if_else("yes", 1, 2) # pc.index_in([1, 2, 3], options=pc.SetLookupOptions(pa.scalar(2))) + # pc.cast(pa.table({"a": [1]}), pa.float32()), pc.cast(pc.field("a"), "int64") def test_agg_functions() -> None: @@ -327,14 +361,14 @@ def test_agg_functions() -> None: check(pc.last(scalar), pa.Int64Scalar) check(pc.first_last(scalar), pa.StructScalar) + # Aggregations return no expression + check(assert_type(pc.mode(arr, n=2), pa.StructArray), pa.StructArray) + # Quantile returns doubles, or the input type for "lower", "higher", "nearest" check(assert_type(pc.quantile(arr, q=[0.25, 0.75]), _Quantile), pa.DoubleArray) check(assert_type(pc.quantile(arr, interpolation="lower"), _Quantile), pa.Int64Array) - check(assert_type(pc.mode(arr, n=2), pa.StructArray), pa.StructArray) - check(pc.mean(arr), pa.DoubleScalar) - # Python lists, tuples and NumPy arrays accepted check(pc.variance([1, 2, 3]), pa.DoubleScalar) check(pc.variance((1, 2, 3)), pa.DoubleScalar) @@ -345,5 +379,6 @@ def test_agg_functions() -> None: check(pc.index(arr, 2), pa.Int64Scalar) # TODO: test invalid code once the scalar stubs are annotated - # Aggregations can't be evaluated as expressions - # ds.dataset(table).to_table(columns={"total": pc.sum(pc.field("a"))}) + # Aggregations can't be evaluated as expressions, e.g. evaluating + # pc.sum(pc.field("a")) in ds.dataset(table).to_table(columns=...) fails: + # pc.sum(pc.field("a")) diff --git a/python/pyarrow-stubs/compute.pyi b/python/pyarrow-stubs/compute.pyi index 77707c03a805..b9c2c82e88b6 100644 --- a/python/pyarrow-stubs/compute.pyi +++ b/python/pyarrow-stubs/compute.pyi @@ -1089,7 +1089,7 @@ def is_in_meta_binary( # ========================= Categorizations ========================= def is_finite( - values: _ScalarOrArray | Expression, + values: _ComputeInput, /, *, memory_pool: MemoryPool | None = None, @@ -1099,7 +1099,7 @@ is_inf = _clone_signature(is_finite) is_nan = _clone_signature(is_finite) def is_null( - values: _ScalarOrArray | Expression, + values: _ComputeInput, /, *, nan_is_null: bool = False, @@ -1107,7 +1107,7 @@ def is_null( memory_pool: MemoryPool | None = None, ) -> BooleanScalar | BooleanArray | ChunkedArray | Expression: ... def is_valid( - values: _ScalarOrArray | _ArrayLike | Expression, + values: _ComputeInput, /, *, memory_pool: MemoryPool | None = None, @@ -1117,24 +1117,24 @@ true_unless_null = _clone_signature(is_valid) # ========================= Selecting / multiplexing ========================= def case_when( - cond: _ScalarOrArray | Expression, + cond: _ComputeInput, /, - *cases: _ScalarOrArray | _ArrayLike, + *cases: _ComputeInput | _Literal, memory_pool: MemoryPool | None = None, -) -> _ScalarOrArray | Array | Expression: ... +) -> _ScalarOrArray | Expression: ... def choose( indices: _ComputeInput | int, /, - *values: _ScalarOrArray | _ArrayLike | _Literal, + *values: _ComputeInput | _Literal, memory_pool: MemoryPool | None = None, ) -> _ScalarOrArray | Expression: ... def coalesce( - *values: _ScalarOrArray | Expression, memory_pool: MemoryPool | None = None + *values: _ComputeInput | _Literal, memory_pool: MemoryPool | None = None ) -> _ScalarOrArray | Expression: ... def if_else( cond: _ComputeInput | bool | np.generic, - left: _ScalarOrArray | _ArrayLike | _Literal, - right: _ScalarOrArray | _ArrayLike | _Literal, + left: _ComputeInput | _Literal, + right: _ComputeInput | _Literal, /, *, memory_pool: MemoryPool | None = None, @@ -1146,7 +1146,7 @@ def fill_null( # ========================= Structural transforms ========================= def list_value_length( - lists: _ArrayOrChunkedArray | Expression, + lists: _ComputeInput, /, *, memory_pool: MemoryPool | None = None, @@ -1154,7 +1154,7 @@ def list_value_length( Int32Scalar | Int64Scalar | Int32Array | Int64Array | ChunkedArray | Expression ): ... def make_struct( - *args: _ScalarOrArray | _ArrayLike | Expression, + *args: _ComputeInput, field_names: Sequence[str] = (), field_nullability: bool | None = None, field_metadata: Sequence[KeyValueMetadata] | None = None, @@ -1164,7 +1164,7 @@ def make_struct( # ========================= Conversions ========================= def ceil_temporal( - timestamps: _ScalarOrArray | Expression, + timestamps: _ComputeInput, /, multiple: int = 1, unit: _DateTimeUnit = "day", @@ -1180,25 +1180,25 @@ floor_temporal = _clone_signature(ceil_temporal) round_temporal = _clone_signature(ceil_temporal) def cast( - arr: _ScalarOrArray | Table, + arr: _ScalarOrArray | _ArrayLike | _Literal, target_type: DataType | str | None = None, safe: bool | None = None, options: CastOptions | None = None, memory_pool: MemoryPool | None = None, -) -> Scalar | Array | ChunkedArray | Table: ... +) -> Scalar | Array | ChunkedArray: ... def strftime( - timestamps: _ScalarOrArray | Expression, + timestamps: _ComputeInput | _TemporalLiteral, /, - format: str = "%Y-%m-%dT%H:%M:%S", + format: str | bytes = "%Y-%m-%dT%H:%M:%S", locale: str = "C", *, options: StrftimeOptions | None = None, memory_pool: MemoryPool | None = None, ) -> StringScalar | StringArray | ChunkedArray | Expression: ... def strptime( - strings: _ScalarOrArray | Expression, + strings: _ComputeInput | str, /, - format: str, + format: str | bytes, unit: TimeUnit, error_is_null: bool = False, *, @@ -1206,19 +1206,19 @@ def strptime( memory_pool: MemoryPool | None = None, ) -> TimestampScalar | TimestampArray | ChunkedArray | Expression: ... def run_end_encode( - array: _ArrayOrChunkedArray | Expression, + array: _ArrayOrChunkedArray | _ArrayLike, /, run_end_type: DataType | str = ..., *, options: RunEndEncodeOptions | None = None, memory_pool: MemoryPool | None = None, -) -> RunEndEncodedArray | ChunkedArray | Expression: ... +) -> RunEndEncodedArray | ChunkedArray: ... def run_end_decode( - array: _ArrayOrChunkedArray | Expression, + array: _ArrayOrChunkedArray | _ArrayLike, /, *, memory_pool: MemoryPool | None = None, -) -> _ArrayOrChunkedArray | Expression: ... +) -> _ArrayOrChunkedArray: ... # ========================= Temporal component extraction ========================= def day( From 27be146d8823d8b7bc1af4f20811060b5e6ea434 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Mon, 23 Nov 2026 11:28:36 +0100 Subject: [PATCH 18/33] Review temporal functions stubs --- python/pyarrow-stubs-tests/test_compute.py | 13 +++++ python/pyarrow-stubs/compute.pyi | 65 +++++++++++----------- 2 files changed, 47 insertions(+), 31 deletions(-) diff --git a/python/pyarrow-stubs-tests/test_compute.py b/python/pyarrow-stubs-tests/test_compute.py index 9eda3b8a5e86..ee6d7b25ee62 100644 --- a/python/pyarrow-stubs-tests/test_compute.py +++ b/python/pyarrow-stubs-tests/test_compute.py @@ -337,8 +337,21 @@ def test_element_wise_functions() -> None: pa.RunEndEncodedArray) check(assert_type(pc.run_end_decode(ree), pa.Array | pa.ChunkedArray), pa.Array) + # Temporal + date = dt.datetime(2026, 1, 1) + check(pc.day(date), pa.Int64Scalar) + check(pc.day([date]), pa.Int64Array) + check(pc.is_leap_year((date,)), pa.BooleanArray) + check(pc.days_between(date, date), pa.Int64Scalar) + check(pc.month_day_nano_interval_between([date], [date]), + pa.MonthDayNanoIntervalArray) + check(pc.years_between((date, ), (date, )), pa.Int64Array) + check(pc.assume_timezone([date], timezone=b"UTC"), pa.TimestampArray) + check(pc.local_timestamp(date), pa.TimestampScalar) + if TYPE_CHECKING: pc.is_in([1, 2, 3], pc.field("a")) # type: ignore[arg-type] + pc.random(3.14) # type: ignore[arg-type] # Fails when evaluated (ds.dataset(table).to_table(columns={"r": ...})): pc.run_end_encode(pc.field("a")) # type: ignore[arg-type] # TODO: test invalid code once the scalar stubs are annotated diff --git a/python/pyarrow-stubs/compute.pyi b/python/pyarrow-stubs/compute.pyi index b9c2c82e88b6..2fc48ffad3a0 100644 --- a/python/pyarrow-stubs/compute.pyi +++ b/python/pyarrow-stubs/compute.pyi @@ -1222,13 +1222,13 @@ def run_end_decode( # ========================= Temporal component extraction ========================= def day( - values: _ScalarOrArray | Expression, + values: _ComputeInput | _TemporalLiteral, /, *, memory_pool: MemoryPool | None = None, ) -> Int64Scalar | Int64Array | ChunkedArray | Expression: ... def day_of_week( - values: _ScalarOrArray | Expression, + values: _ComputeInput | _TemporalLiteral, /, *, count_from_zero: bool = True, @@ -1240,19 +1240,19 @@ def day_of_week( day_of_year = _clone_signature(day) def hour( - values: _ScalarOrArray | Expression, + values: _ComputeInput | _TemporalLiteral, /, *, memory_pool: MemoryPool | None = None, ) -> Int64Scalar | Int64Array | ChunkedArray | Expression: ... def is_dst( - values: _ScalarOrArray | Expression, + values: _ComputeInput | _TemporalLiteral, /, *, memory_pool: MemoryPool | None = None, ) -> BooleanScalar | BooleanArray | ChunkedArray | Expression: ... def iso_week( - values: _ScalarOrArray | Expression, + values: _ComputeInput | _TemporalLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -1261,7 +1261,7 @@ def iso_week( iso_year = _clone_signature(iso_week) def is_leap_year( - values: _ScalarOrArray | Expression, + values: _ComputeInput | _TemporalLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -1279,7 +1279,7 @@ us_week = _clone_signature(iso_week) us_year = _clone_signature(iso_week) def week( - values: _ScalarOrArray | Expression, + values: _ComputeInput | _TemporalLiteral, /, *, week_starts_monday: bool = True, @@ -1292,7 +1292,7 @@ def week( year = _clone_signature(iso_week) def year_month_day( - values: _ScalarOrArray | Expression, + values: _ComputeInput | _TemporalLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -1301,16 +1301,17 @@ def year_month_day( iso_calendar = _clone_signature(year_month_day) # ========================= Temporal difference ========================= -def day_time_interval_between( - start: _ScalarOrArray | Expression, - end: _ScalarOrArray | Expression, - /, - *, - memory_pool: MemoryPool | None = None, -) -> _ScalarOrArray | Expression: ... +# TODO(GH-29828): add once PyArrow supports DayTimeInterval type +# def day_time_interval_between( +# start: _ComputeInput | _TemporalLiteral, +# end: _ComputeInput | _TemporalLiteral, +# /, +# *, +# memory_pool: MemoryPool | None = None, +# ) -> _ScalarOrArray | Expression: ... def days_between( - start: _ScalarOrArray | Expression, - end: _ScalarOrArray | Expression, + start: _ComputeInput | _TemporalLiteral, + end: _ComputeInput | _TemporalLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -1322,29 +1323,31 @@ milliseconds_between = _clone_signature(days_between) minutes_between = _clone_signature(days_between) def month_day_nano_interval_between( - start: _ScalarOrArray | Expression, - end: _ScalarOrArray | Expression, + start: _ComputeInput | _TemporalLiteral, + end: _ComputeInput | _TemporalLiteral, /, *, memory_pool: MemoryPool | None = None, ) -> ( MonthDayNanoIntervalScalar | MonthDayNanoIntervalArray | ChunkedArray | Expression ): ... -def month_interval_between( - start: _ScalarOrArray | Expression, - end: _ScalarOrArray | Expression, - /, - *, - memory_pool: MemoryPool | None = None, -) -> _ScalarOrArray | Expression: ... + +# TODO(GH-29828): add once PyArrow supports MonthInterval type +# def month_interval_between( +# start: _ComputeInput | _TemporalLiteral, +# end: _ComputeInput | _TemporalLiteral, +# /, +# *, +# memory_pool: MemoryPool | None = None, +# ) -> _ScalarOrArray | Expression: ... nanoseconds_between = _clone_signature(days_between) quarters_between = _clone_signature(days_between) seconds_between = _clone_signature(days_between) def weeks_between( - start: _ScalarOrArray | Expression, - end: _ScalarOrArray | Expression, + start: _ComputeInput | _TemporalLiteral, + end: _ComputeInput | _TemporalLiteral, /, *, count_from_zero: bool = True, @@ -1357,9 +1360,9 @@ years_between = _clone_signature(days_between) # ========================= Timezone handling ========================= def assume_timezone( - timestamps: _ScalarOrArray | Expression, + timestamps: _ComputeInput | _TemporalLiteral, /, - timezone: str, + timezone: str | bytes, *, ambiguous: _TimezoneResolution = "raise", nonexistent: _TimezoneResolution = "raise", @@ -1367,7 +1370,7 @@ def assume_timezone( memory_pool: MemoryPool | None = None, ) -> TimestampScalar | TimestampArray | ChunkedArray | Expression: ... def local_timestamp( - values: _ScalarOrArray | Expression, + values: _ComputeInput | _TemporalLiteral, /, *, memory_pool: MemoryPool | None = None, From f5c4874ad93ac7ea95fa7f5b85ed8fac58ae9dd8 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Tue, 24 Nov 2026 11:19:50 +0100 Subject: [PATCH 19/33] Review the rest of compute.pyi --- python/pyarrow-stubs-tests/test_compute.py | 101 +++++++++++++--- python/pyarrow-stubs/compute.pyi | 130 +++++++++++---------- 2 files changed, 153 insertions(+), 78 deletions(-) diff --git a/python/pyarrow-stubs-tests/test_compute.py b/python/pyarrow-stubs-tests/test_compute.py index ee6d7b25ee62..e6d14f0022f6 100644 --- a/python/pyarrow-stubs-tests/test_compute.py +++ b/python/pyarrow-stubs-tests/test_compute.py @@ -28,9 +28,7 @@ from _check import assert_type, check -_Filtered: TypeAlias = ( - pa.Array | pa.ChunkedArray | pa.RecordBatch | pa.Table | pc.Expression -) +_Filtered: TypeAlias = pa.Array | pa.ChunkedArray | pa.RecordBatch | pa.Table _Quantile: TypeAlias = ( pa.NumericArray @@ -40,6 +38,17 @@ | pa.Decimal256Array ) +_Numeric: TypeAlias = ( + pa.NumericArray + | pa.Decimal32Array + | pa.Decimal64Array + | pa.Decimal128Array + | pa.Decimal256Array + | pa.ChunkedArray +) + +_NumericOrTemporal: TypeAlias = _Quantile | pa.MonthDayNanoIntervalArray + def test_expression() -> None: # Field references and literals @@ -170,50 +179,108 @@ def test_array_wise_functions() -> None: table = pa.table({"a": [3, 1, 2]}) # Sorts and selections - check(assert_type(pc.array_sort_indices(arr), pa.UInt64Array | pc.Expression), + check(assert_type(pc.array_sort_indices(arr), pa.UInt64Array | pa.ChunkedArray), pa.UInt64Array) + check(assert_type(pc.array_sort_indices(pa.chunked_array([[3, 1], [2]])), + pa.UInt64Array | pa.ChunkedArray), + pa.ChunkedArray) check(assert_type(pc.sort_indices(table, [("a", "descending")]), - pa.UInt64Array | pc.Expression), + pa.UInt64Array), pa.UInt64Array) check(assert_type(pc.sort_indices(table, [(0, "descending")]), - pa.UInt64Array | pc.Expression), + pa.UInt64Array), pa.UInt64Array) check(assert_type(pc.top_k_unstable(arr, 2), pa.UInt64Array), pa.UInt64Array) check(assert_type(pc.bottom_k_unstable(table, 2, ["a"], ["at_end"]), pa.UInt64Array), pa.UInt64Array) - check(assert_type(pc.indices_nonzero(arr), pa.UInt64Array | pc.Expression), + check(assert_type(pc.indices_nonzero(arr), pa.UInt64Array), pa.UInt64Array) - check(assert_type(pc.value_counts(arr), pa.StructArray | pc.Expression), + check(assert_type(pc.value_counts(arr), pa.StructArray), pa.StructArray) - # Filters keep the input kind: table, array or expression + # Filters keep the input kind: table or array mask = pa.array([True, False, True]) check(assert_type(pc.filter(table, mask), _Filtered), pa.Table) check(assert_type(pc.drop_null(table), _Filtered), pa.Table) - check(assert_type(pc.filter(pc.field("a"), pc.field("b")), - _Filtered), - pc.Expression) # Python lists and tuples accepted - check(assert_type(pc.partition_nth_indices([3, 1, 2], pivot=1), - pa.UInt64Array | pc.Expression), - pa.UInt64Array) + check(assert_type(pc.winsorize([10, 4, 0], 0.1, 0.8), _Numeric), pa.Array) + dictionary = pc.dictionary_encode(["a", "b", "a"]) + check(assert_type(dictionary, pa.DictionaryArray | pa.ChunkedArray), + pa.DictionaryArray) + check(assert_type(pc.dictionary_encode(pa.scalar("a")), + pa.DictionaryArray | pa.ChunkedArray), + pa.DictionaryArray) + check(assert_type(pc.dictionary_decode(dictionary), pa.Array | pa.ChunkedArray), + pa.StringArray) + check(assert_type(pc.unique([1, 2, 1]), pa.Array), pa.Int64Array) + check(assert_type(pc.unique(pa.scalar("b")), pa.Array), pa.StringArray) + check(assert_type(pc.unique(pa.chunked_array([[1], [2]])), pa.Array), pa.Int64Array) + check(assert_type(pc.array_filter([1, 2, 3], [True, False, False]), + pa.Array | pa.ChunkedArray), pa.Int64Array) + check(assert_type(pc.inverse_permutation([1, 2, 0]), + pa.IntegerArray | pa.ChunkedArray), pa.Int64Array) + check(assert_type(pc.scatter([True, True, False, True], [0, 1, 3, 2]), + pa.Array | pa.ChunkedArray), pa.BooleanArray) taken = pc.take(arr, [0, 2]) check(assert_type(taken, pa.Array | pa.ChunkedArray | pa.RecordBatch | pa.Table), pa.Array) + check(assert_type(pc.partition_nth_indices([3, 1, 2], pivot=1), + pa.UInt64Array | pa.ChunkedArray), + pa.UInt64Array) + check(assert_type(pc.partition_nth_indices(pa.chunked_array([[3, 1], [2]]), + pivot=1), + pa.UInt64Array | pa.ChunkedArray), + pa.ChunkedArray) + check(assert_type(pc.search_sorted([1, 2, 3], [0, 1, 2]), + pa.UInt64Scalar | pa.UInt64Array), + pa.UInt64Array) + # Chunked needles give a plain array + check(assert_type(pc.search_sorted([1, 2, 3], pa.chunked_array([[0], [2]])), + pa.UInt64Scalar | pa.UInt64Array), + pa.UInt64Array) + + # Containment tests + check(assert_type(pc.indices_nonzero(1), pa.UInt64Array), pa.UInt64Array) # Structural transforms + check(pc.list_contains([[1, 2, 3]], 1), pa.BooleanArray) + check(pc.list_element([[1, 2, 3]], 1), pa.Int64Array) + check(assert_type(pc.list_flatten([[1, 2], [3]]), pa.Array | pa.ChunkedArray), + pa.Int64Array) + check(assert_type(pc.list_flatten(pa.scalar([1, 2])), pa.Array | pa.ChunkedArray), + pa.Int64Array) + check(assert_type(pc.list_parent_indices(pa.chunked_array([[[1, 2], [3]]])), + pa.Int64Array | pa.ChunkedArray), + pa.ChunkedArray) check(pc.struct_field(pa.array([{"a": 1}]), ("a",)), pa.Array) - # Replacements as an array or a Python list - check(pc.replace_with_mask(arr, mask, pa.array([10, 30])), pa.Int64Array) + # Replace functions always return arrays + check(assert_type(pc.fill_null_forward([1, None]), pa.Array | pa.ChunkedArray), + pa.Int64Array) + check(assert_type(pc.fill_null_backward([None, 1]), pa.Array | pa.ChunkedArray), + pa.Int64Array) + # Replacements as an array, a scalar or a Python list + check(assert_type(pc.replace_with_mask(arr, mask, pa.array([10, 30])), + pa.Array | pa.ChunkedArray), + pa.Int64Array) + check(pc.replace_with_mask(arr, mask, pa.scalar(10)), pa.Int64Array) check(pc.replace_with_mask(arr, mask, [10, 30]), pa.Int64Array) + # Pairwise functions + check(assert_type(pc.pairwise_diff([1, 3, 6]), _NumericOrTemporal), pa.Int64Array) + if TYPE_CHECKING: pc.top_k_unstable(arr, "2") # type: ignore[arg-type] + pc.top_k_unstable([3, 1, 2], 2) # type: ignore[arg-type] pc.sort_indices(table, [("a", "up")]) # type: ignore[list-item] + # Only lists, tuples and NumPy arrays are converted to arrays (_ArrayLike) pc.cumulative_sum(range(3)) # type: ignore[arg-type] + # Vector and meta functions can't be evaluated as expressions, e.g. + # ds.dataset(table).to_table(columns={"r": ...}) fails for them + pc.filter(pc.field("a"), pc.field("b")) # type: ignore[arg-type] + pc.pairwise_diff(pa.chunked_array([[1, 3, 6]])) # type: ignore[arg-type] # TODO: test invalid code once the scalar stubs are annotated # pc.variance(range(3)), pc.round("abc") diff --git a/python/pyarrow-stubs/compute.pyi b/python/pyarrow-stubs/compute.pyi index 2fc48ffad3a0..39b1a58c1028 100644 --- a/python/pyarrow-stubs/compute.pyi +++ b/python/pyarrow-stubs/compute.pyi @@ -184,6 +184,7 @@ from pyarrow.lib import ( Decimal64Array, Decimal128Array, Decimal256Array, + DictionaryArray, DoubleArray, DurationArray, FixedSizeBinaryArray, @@ -1389,14 +1390,14 @@ def random( # ========================= Cumulative Functions ========================= def cumulative_sum( - values: _ArrayOrChunkedArray | _ArrayLike | Expression, + values: _ArrayOrChunkedArray | _ArrayLike, /, start: float | Scalar | None = None, *, skip_nulls: bool = False, options: CumulativeOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _NumericArray | ChunkedArray | Expression: ... +) -> _NumericArray | ChunkedArray: ... cumulative_sum_checked = _clone_signature(cumulative_sum) cumulative_prod = _clone_signature(cumulative_sum) @@ -1407,97 +1408,97 @@ cumulative_mean = _clone_signature(cumulative_sum) # ========================= Statistical functions ========================= def winsorize( - array: _ArrayOrChunkedArray | Expression, + array: _ScalarOrArray | _ArrayLike, /, lower_limit: float, upper_limit: float, *, options: WinsorizeOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _NumericArray | ChunkedArray | Expression: ... +) -> _NumericArray | ChunkedArray: ... # ========================= Associative transforms ========================= def dictionary_encode( - array: _ScalarOrArray | Expression, + array: _ScalarOrArray | _ArrayLike, /, null_encoding: NullEncoding = "mask", *, options: DictionaryEncodeOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _ScalarOrArray | Expression: ... +) -> DictionaryArray | ChunkedArray: ... def unique( - array: _ArrayOrChunkedArray | Expression, + array: _ScalarOrArray | _ArrayLike, /, *, memory_pool: MemoryPool | None = None, -) -> _ArrayOrChunkedArray | Expression: ... +) -> Array: ... def value_counts( - array: _ArrayOrChunkedArray | Expression, + array: _ScalarOrArray | _ArrayLike, /, *, memory_pool: MemoryPool | None = None, -) -> StructArray | Expression: ... +) -> StructArray: ... def dictionary_decode( - dictionary_array: _ScalarOrArray | Expression, + dictionary_array: _ArrayOrChunkedArray, /, *, memory_pool: MemoryPool | None = None, -) -> _ScalarOrArray | Expression: ... +) -> _ArrayOrChunkedArray: ... # ========================= Selections ========================= def array_filter( - array: _ArrayOrChunkedArray | Expression, - selection_filter: Mask | Expression, + array: _ArrayOrChunkedArray | _ArrayLike, + selection_filter: Mask, /, null_selection_behavior: NullSelectionBehavior = "drop", *, options: FilterOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _ArrayOrChunkedArray | Expression: ... +) -> _ArrayOrChunkedArray: ... def array_take( - array: _ArrayOrChunkedArray | RecordBatch | Table | Expression, - indices: Indices | Expression, + array: _ArrayOrChunkedArray | _ArrayLike, + indices: Indices, /, *, boundscheck: bool = True, options: TakeOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _ArrayOrChunkedArray | RecordBatch | Table | Expression: ... +) -> _ArrayOrChunkedArray: ... def drop_null( - input: _ArrayOrChunkedArray | RecordBatch | Table | Expression, + input: _ArrayOrChunkedArray | _ArrayLike | RecordBatch | Table, /, *, memory_pool: MemoryPool | None = None, -) -> _ArrayOrChunkedArray | RecordBatch | Table | Expression: ... +) -> _ArrayOrChunkedArray | RecordBatch | Table: ... def filter( - input: _ArrayOrChunkedArray | RecordBatch | Table | Expression, - selection_filter: Mask | Expression, + input: _ArrayOrChunkedArray | _ArrayLike | RecordBatch | Table, + selection_filter: Mask, /, null_selection_behavior: NullSelectionBehavior = "drop", *, options: FilterOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _ArrayOrChunkedArray | RecordBatch | Table | Expression: ... +) -> _ArrayOrChunkedArray | RecordBatch | Table: ... def inverse_permutation( - indices: _ArrayOrChunkedArray | Expression, + indices: _ArrayOrChunkedArray | _ArrayLike, /, max_index: int = -1, output_type: DataType | str | None = None, *, options: InversePermutationOptions | None = None, memory_pool: MemoryPool | None = None, -) -> IntegerArray | ChunkedArray | Expression: ... +) -> IntegerArray | ChunkedArray: ... def scatter( - values: _ArrayOrChunkedArray | Expression, - indices: _ArrayOrChunkedArray | Expression, + values: _ArrayOrChunkedArray | _ArrayLike, + indices: _ArrayOrChunkedArray | _ArrayLike, /, max_index: int = -1, *, options: ScatterOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _ArrayOrChunkedArray | Expression: ... +) -> _ArrayOrChunkedArray: ... def take( - data: _ArrayOrChunkedArray | RecordBatch | Table, + data: _ArrayOrChunkedArray | _ArrayLike | RecordBatch | Table, indices: Indices, *, boundscheck: bool = True, @@ -1506,33 +1507,33 @@ def take( # ========================= Containment tests ========================= def indices_nonzero( - values: _ArrayOrChunkedArray | Expression, + values: _ArrayOrChunkedArray | _ArrayLike | int, /, *, memory_pool: MemoryPool | None = None, -) -> UInt64Array | Expression: ... +) -> UInt64Array: ... # ========================= Sorts and partitions ========================= def array_sort_indices( - array: _ArrayOrChunkedArray | Expression, + array: _ArrayOrChunkedArray | _ArrayLike, /, order: Order = "ascending", *, null_placement: NullPlacement = "at_end", options: ArraySortOptions | None = None, memory_pool: MemoryPool | None = None, -) -> UInt64Array | Expression: ... +) -> UInt64Array | ChunkedArray: ... def partition_nth_indices( - array: _ArrayOrChunkedArray | _ArrayLike | Expression, + array: _ArrayOrChunkedArray | _ArrayLike, /, pivot: int, *, null_placement: NullPlacement = "at_end", options: PartitionNthOptions | None = None, memory_pool: MemoryPool | None = None, -) -> UInt64Array | Expression: ... +) -> UInt64Array | ChunkedArray: ... def rank( - input: _ArrayOrChunkedArray, + input: _ArrayOrChunkedArray | _ArrayLike, /, sort_keys: Order | Sequence[_SortKey] = "ascending", *, @@ -1542,7 +1543,7 @@ def rank( memory_pool: MemoryPool | None = None, ) -> UInt64Array: ... def rank_normal( - input: _ArrayOrChunkedArray, + input: _ArrayOrChunkedArray | _ArrayLike, /, sort_keys: Order | Sequence[_SortKey] = "ascending", *, @@ -1551,7 +1552,7 @@ def rank_normal( memory_pool: MemoryPool | None = None, ) -> DoubleArray: ... def rank_quantile( - input: _ArrayOrChunkedArray, + input: _ArrayOrChunkedArray | _ArrayLike, /, sort_keys: Order | Sequence[_SortKey] = "ascending", *, @@ -1560,32 +1561,32 @@ def rank_quantile( memory_pool: MemoryPool | None = None, ) -> DoubleArray: ... def select_k_unstable( - input: _ArrayOrChunkedArray | RecordBatch | Table | Expression, + input: _ArrayOrChunkedArray | _ArrayLike | RecordBatch | Table, /, k: int, sort_keys: Sequence[_SortKey], *, options: SelectKOptions | None = None, memory_pool: MemoryPool | None = None, -) -> UInt64Array | Expression: ... +) -> UInt64Array: ... def sort_indices( - input: _ArrayOrChunkedArray | RecordBatch | Table | Expression, + input: _ArrayOrChunkedArray | _ArrayLike | RecordBatch | Table, /, sort_keys: Sequence[_SortKey] = (), *, null_placement: NullPlacement | None = None, options: SortOptions | None = None, memory_pool: MemoryPool | None = None, -) -> UInt64Array | Expression: ... +) -> UInt64Array: ... def search_sorted( - values: _ArrayOrChunkedArray | Expression, - needles: _ScalarOrArray | _Literal | Expression, + values: _ArrayOrChunkedArray | _ArrayLike, + needles: _ScalarOrArray | _ArrayLike | _Literal, /, side: _Side = "left", *, options: SearchSortedOptions | None = None, memory_pool: MemoryPool | None = None, -) -> UInt64Scalar | UInt64Array | ChunkedArray | Expression: ... +) -> UInt64Scalar | UInt64Array: ... def top_k_unstable( values: _ArrayOrChunkedArray | RecordBatch | Table, k: int, @@ -1604,29 +1605,36 @@ def bottom_k_unstable( ) -> UInt64Array: ... # ========================= Structural transforms ========================= +def list_contains( + lists: _ComputeInput, + value: _ComputeInput | _Literal, + /, + *, + memory_pool: MemoryPool | None = None, +) -> BooleanScalar | BooleanArray | Expression: ... def list_element( - lists: _ScalarOrArray | Expression, - index: int | Scalar | Expression, + lists: _ComputeInput, + index: _ComputeInput | int, /, *, memory_pool: MemoryPool | None = None, ) -> _ScalarOrArray | Expression: ... def list_flatten( - lists: _ArrayOrChunkedArray | Expression, + lists: _ScalarOrArray | _ArrayLike, /, recursive: bool = False, *, options: ListFlattenOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _ArrayOrChunkedArray | Expression: ... +) -> _ArrayOrChunkedArray: ... def list_parent_indices( - lists: _ArrayOrChunkedArray | Expression, + lists: _ArrayOrChunkedArray | _ArrayLike, /, *, memory_pool: MemoryPool | None = None, -) -> Int64Array | Expression: ... +) -> Int64Array | ChunkedArray: ... def list_slice( - lists: _ArrayOrChunkedArray | Expression, + lists: _ComputeInput, /, start: int, stop: int | None = None, @@ -1656,34 +1664,34 @@ def struct_field( # ========================= Replace functions ========================= def fill_null_backward( - values: _ScalarOrArray | _Literal | Expression, + values: _ArrayOrChunkedArray | _ArrayLike, /, *, memory_pool: MemoryPool | None = None, -) -> _ScalarOrArray | Expression: ... +) -> _ArrayOrChunkedArray: ... def fill_null_forward( - values: _ScalarOrArray | _Literal | Expression, + values: _ArrayOrChunkedArray | _ArrayLike, /, *, memory_pool: MemoryPool | None = None, -) -> _ScalarOrArray | Expression: ... +) -> _ArrayOrChunkedArray: ... def replace_with_mask( - values: _ScalarOrArray | Expression, + values: _ArrayOrChunkedArray | _ArrayLike, mask: Mask, - replacements: _ArrayOrChunkedArray | _ArrayLike, + replacements: _ScalarOrArray | _ArrayLike, /, *, memory_pool: MemoryPool | None = None, -) -> _ScalarOrArray | Expression: ... +) -> _ArrayOrChunkedArray: ... # ========================= Pairwise functions ========================= def pairwise_diff( - input: _ArrayOrChunkedArray | Expression, + input: Array | _ArrayLike, /, period: int = 1, *, options: PairwiseOptions | None = None, memory_pool: MemoryPool | None = None, -) -> _NumericOrTemporalArray | ChunkedArray | Expression: ... +) -> _NumericOrTemporalArray: ... pairwise_diff_checked = _clone_signature(pairwise_diff) From 908e02c9db2b34343c810991a2536976e7fd3e70 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Wed, 25 Nov 2026 06:14:41 +0100 Subject: [PATCH 20/33] Fix segfault in partition_nth_indices --- python/pyarrow-stubs-tests/test_compute.py | 10 ++++------ python/pyarrow-stubs/compute.pyi | 4 ++-- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/python/pyarrow-stubs-tests/test_compute.py b/python/pyarrow-stubs-tests/test_compute.py index e6d14f0022f6..3d99ec69588e 100644 --- a/python/pyarrow-stubs-tests/test_compute.py +++ b/python/pyarrow-stubs-tests/test_compute.py @@ -226,13 +226,8 @@ def test_array_wise_functions() -> None: taken = pc.take(arr, [0, 2]) check(assert_type(taken, pa.Array | pa.ChunkedArray | pa.RecordBatch | pa.Table), pa.Array) - check(assert_type(pc.partition_nth_indices([3, 1, 2], pivot=1), - pa.UInt64Array | pa.ChunkedArray), + check(assert_type(pc.partition_nth_indices([3, 1, 2], pivot=1), pa.UInt64Array), pa.UInt64Array) - check(assert_type(pc.partition_nth_indices(pa.chunked_array([[3, 1], [2]]), - pivot=1), - pa.UInt64Array | pa.ChunkedArray), - pa.ChunkedArray) check(assert_type(pc.search_sorted([1, 2, 3], [0, 1, 2]), pa.UInt64Scalar | pa.UInt64Array), pa.UInt64Array) @@ -275,6 +270,9 @@ def test_array_wise_functions() -> None: pc.top_k_unstable(arr, "2") # type: ignore[arg-type] pc.top_k_unstable([3, 1, 2], 2) # type: ignore[arg-type] pc.sort_indices(table, [("a", "up")]) # type: ignore[list-item] + # TODO: currently segfaults + # pc.partition_nth_indices( + # pa.chunked_array([[3, 1], [2]]), pivot=1) # Only lists, tuples and NumPy arrays are converted to arrays (_ArrayLike) pc.cumulative_sum(range(3)) # type: ignore[arg-type] # Vector and meta functions can't be evaluated as expressions, e.g. diff --git a/python/pyarrow-stubs/compute.pyi b/python/pyarrow-stubs/compute.pyi index 39b1a58c1028..d392f9032f99 100644 --- a/python/pyarrow-stubs/compute.pyi +++ b/python/pyarrow-stubs/compute.pyi @@ -1524,14 +1524,14 @@ def array_sort_indices( memory_pool: MemoryPool | None = None, ) -> UInt64Array | ChunkedArray: ... def partition_nth_indices( - array: _ArrayOrChunkedArray | _ArrayLike, + array: Array | _ArrayLike, /, pivot: int, *, null_placement: NullPlacement = "at_end", options: PartitionNthOptions | None = None, memory_pool: MemoryPool | None = None, -) -> UInt64Array | ChunkedArray: ... +) -> UInt64Array: ... def rank( input: _ArrayOrChunkedArray | _ArrayLike, /, From 07a6c8302739baf0a1bc299aa22cd8a7679cc94b Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Wed, 25 Nov 2026 06:26:35 +0100 Subject: [PATCH 21/33] Update comment for partition_nth_indices test --- python/pyarrow-stubs-tests/test_compute.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/pyarrow-stubs-tests/test_compute.py b/python/pyarrow-stubs-tests/test_compute.py index 3d99ec69588e..67ac37bfdd5e 100644 --- a/python/pyarrow-stubs-tests/test_compute.py +++ b/python/pyarrow-stubs-tests/test_compute.py @@ -270,7 +270,7 @@ def test_array_wise_functions() -> None: pc.top_k_unstable(arr, "2") # type: ignore[arg-type] pc.top_k_unstable([3, 1, 2], 2) # type: ignore[arg-type] pc.sort_indices(table, [("a", "up")]) # type: ignore[list-item] - # TODO: currently segfaults + # TODO(GH-55775): # pc.partition_nth_indices( # pa.chunked_array([[3, 1], [2]]), pivot=1) # Only lists, tuples and NumPy arrays are converted to arrays (_ArrayLike) From 00e0461e74c44daca3db22ad3a5d8639b047c759 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Wed, 25 Nov 2026 07:55:31 +0100 Subject: [PATCH 22/33] Remove _compute_docstrings.pyi --- python/pyarrow-stubs/_compute_docstrings.pyi | 18 ------------------ 1 file changed, 18 deletions(-) delete mode 100644 python/pyarrow-stubs/_compute_docstrings.pyi diff --git a/python/pyarrow-stubs/_compute_docstrings.pyi b/python/pyarrow-stubs/_compute_docstrings.pyi deleted file mode 100644 index 514a4e4269c6..000000000000 --- a/python/pyarrow-stubs/_compute_docstrings.pyi +++ /dev/null @@ -1,18 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you 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. - -function_doc_additions: dict[str, str] From 94a71de5ec710c8ba539ffaa870420b4bee7a3c5 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Fri, 27 Nov 2026 06:28:17 +0100 Subject: [PATCH 23/33] Copilot review - register_* methods and in_types stubs --- python/pyarrow-stubs/_compute.pyi | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/python/pyarrow-stubs/_compute.pyi b/python/pyarrow-stubs/_compute.pyi index 15d37174cef5..f2ac5a188a68 100644 --- a/python/pyarrow-stubs/_compute.pyi +++ b/python/pyarrow-stubs/_compute.pyi @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -from collections.abc import Callable, Hashable, Iterable, Mapping, Sequence +from collections.abc import Callable, Hashable, Iterable, Sequence from types import EllipsisType from typing import Any, ClassVar, Literal, Protocol, TypeAlias, TypedDict @@ -520,7 +520,7 @@ def register_scalar_function( func: Callable[..., Any], function_name: str, function_doc: _FunctionDoc | dict[str, str], - in_types: Mapping[str, DataType | str], + in_types: dict[str, DataType | str], out_type: DataType | str, func_registry: FunctionRegistry | None = None, ) -> None: ... @@ -528,7 +528,7 @@ def register_vector_function( func: Callable[..., Any], function_name: str, function_doc: _FunctionDoc | dict[str, str], - in_types: Mapping[str, DataType | str], + in_types: dict[str, DataType | str], out_type: DataType | str, func_registry: FunctionRegistry | None = None, ) -> None: ... @@ -536,7 +536,7 @@ def register_aggregate_function( func: Callable[..., Any], function_name: str, function_doc: _FunctionDoc | dict[str, str], - in_types: Mapping[str, DataType | str], + in_types: dict[str, DataType | str], out_type: DataType | str, func_registry: FunctionRegistry | None = None, ) -> None: ... @@ -544,7 +544,7 @@ def register_tabular_function( func: Callable[..., Any], function_name: str, function_doc: _FunctionDoc | dict[str, str], - in_types: Mapping[str, DataType | str], + in_types: dict[str, DataType | str], out_type: DataType | str, func_registry: FunctionRegistry | None = None, ) -> None: ... From 75e130f4c14e2a6e3a7ba424789284f26e6afb00 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Fri, 27 Nov 2026 06:41:14 +0100 Subject: [PATCH 24/33] Copilot review: register_tabular_function and extract_regex --- python/pyarrow-stubs/_compute.pyi | 2 +- python/pyarrow-stubs/compute.pyi | 12 +++++++++--- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/python/pyarrow-stubs/_compute.pyi b/python/pyarrow-stubs/_compute.pyi index f2ac5a188a68..ad7e7b8a1b5d 100644 --- a/python/pyarrow-stubs/_compute.pyi +++ b/python/pyarrow-stubs/_compute.pyi @@ -545,7 +545,7 @@ def register_tabular_function( function_name: str, function_doc: _FunctionDoc | dict[str, str], in_types: dict[str, DataType | str], - out_type: DataType | str, + out_type: Schema | DataType | str, func_registry: FunctionRegistry | None = None, ) -> None: ... def call_tabular_function( diff --git a/python/pyarrow-stubs/compute.pyi b/python/pyarrow-stubs/compute.pyi index d392f9032f99..6ad0f319a079 100644 --- a/python/pyarrow-stubs/compute.pyi +++ b/python/pyarrow-stubs/compute.pyi @@ -964,7 +964,7 @@ def split_pattern( *, max_splits: int | None = None, reverse: bool = False, - options: SplitOptions | None = None, + options: SplitPatternOptions | None = None, memory_pool: MemoryPool | None = None, ) -> _ListScalar | BaseListArray | ChunkedArray | Expression: ... @@ -980,8 +980,14 @@ def extract_regex( options: ExtractRegexOptions | None = None, memory_pool: MemoryPool | None = None, ) -> StructScalar | StructArray | ChunkedArray | Expression: ... - -extract_regex_span = _clone_signature(extract_regex) +def extract_regex_span( + strings: _ComputeInput | str | bytes, + /, + pattern: str | bytes, + *, + options: ExtractRegexSpanOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> StructScalar | StructArray | ChunkedArray | Expression: ... # ========================= String joining ========================= def binary_join( From 61e9013acf007b5e626646d02760eac45c679f58 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Fri, 27 Nov 2026 07:58:19 +0100 Subject: [PATCH 25/33] Copilot review - make_struct update --- python/pyarrow-stubs-tests/test_compute.py | 3 +++ python/pyarrow-stubs/compute.pyi | 4 ++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/python/pyarrow-stubs-tests/test_compute.py b/python/pyarrow-stubs-tests/test_compute.py index 67ac37bfdd5e..6190bdfcd60f 100644 --- a/python/pyarrow-stubs-tests/test_compute.py +++ b/python/pyarrow-stubs-tests/test_compute.py @@ -353,6 +353,8 @@ def test_element_wise_functions() -> None: check(pc.fill_null(pa.array([1, None]), 5), pa.Int64Array) check(pc.equal([1, 2, 1], [1, 2, 3]), pa.BooleanArray) + check(pc.make_struct(1, 'a', field_nullability=[True]), pa.StructScalar) + check(pc.make_struct(1, 'a', field_metadata=[None]), pa.StructScalar) cond = pc.make_struct([True, False], [False, None]) check(pc.case_when(cond, [1, 2], [12, 13]), pa.Int64Array) cond = pa.scalar({"a": False, "b": True}) @@ -417,6 +419,7 @@ def test_element_wise_functions() -> None: if TYPE_CHECKING: pc.is_in([1, 2, 3], pc.field("a")) # type: ignore[arg-type] pc.random(3.14) # type: ignore[arg-type] + pc.make_struct(1, 'a', field_nullability=True) # type: ignore[arg-type] # Fails when evaluated (ds.dataset(table).to_table(columns={"r": ...})): pc.run_end_encode(pc.field("a")) # type: ignore[arg-type] # TODO: test invalid code once the scalar stubs are annotated diff --git a/python/pyarrow-stubs/compute.pyi b/python/pyarrow-stubs/compute.pyi index 6ad0f319a079..d97f0e06769f 100644 --- a/python/pyarrow-stubs/compute.pyi +++ b/python/pyarrow-stubs/compute.pyi @@ -1163,8 +1163,8 @@ def list_value_length( def make_struct( *args: _ComputeInput, field_names: Sequence[str] = (), - field_nullability: bool | None = None, - field_metadata: Sequence[KeyValueMetadata] | None = None, + field_nullability: Sequence[bool] | None = None, + field_metadata: Sequence[KeyValueMetadata | None] | None = None, options: MakeStructOptions | None = None, memory_pool: MemoryPool | None = None, ) -> StructScalar | StructArray | ChunkedArray | Expression: ... From 2590dc6f8b2caf9a78d89da34f377ead15814c4d Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Fri, 27 Nov 2026 08:06:16 +0100 Subject: [PATCH 26/33] Copilot review - subsecond update --- python/pyarrow-stubs-tests/test_compute.py | 2 ++ python/pyarrow-stubs/compute.pyi | 9 ++++++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/python/pyarrow-stubs-tests/test_compute.py b/python/pyarrow-stubs-tests/test_compute.py index 6190bdfcd60f..86da191cd6fc 100644 --- a/python/pyarrow-stubs-tests/test_compute.py +++ b/python/pyarrow-stubs-tests/test_compute.py @@ -408,6 +408,8 @@ def test_element_wise_functions() -> None: date = dt.datetime(2026, 1, 1) check(pc.day(date), pa.Int64Scalar) check(pc.day([date]), pa.Int64Array) + check(pc.hour(date), pa.Int64Scalar) + check(pc.subsecond(date), pa.DoubleScalar) check(pc.is_leap_year((date,)), pa.BooleanArray) check(pc.days_between(date, date), pa.Int64Scalar) check(pc.month_day_nano_interval_between([date], [date]), diff --git a/python/pyarrow-stubs/compute.pyi b/python/pyarrow-stubs/compute.pyi index d97f0e06769f..894e70ccc078 100644 --- a/python/pyarrow-stubs/compute.pyi +++ b/python/pyarrow-stubs/compute.pyi @@ -1281,7 +1281,14 @@ month = _clone_signature(day) nanosecond = _clone_signature(hour) quarter = _clone_signature(day) second = _clone_signature(hour) -subsecond = _clone_signature(hour) + +def subsecond( + values: _ComputeInput | _TemporalLiteral, + /, + *, + memory_pool: MemoryPool | None = None, +) -> DoubleScalar | DoubleArray | ChunkedArray | Expression: ... + us_week = _clone_signature(iso_week) us_year = _clone_signature(iso_week) From 7ed41c194462fc071b429518488cf6bd756fe75e Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Fri, 27 Nov 2026 08:29:22 +0100 Subject: [PATCH 27/33] Copilot review - list_contains update --- python/pyarrow-stubs-tests/test_compute.py | 1 + python/pyarrow-stubs/compute.pyi | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/python/pyarrow-stubs-tests/test_compute.py b/python/pyarrow-stubs-tests/test_compute.py index 86da191cd6fc..649d513d8a77 100644 --- a/python/pyarrow-stubs-tests/test_compute.py +++ b/python/pyarrow-stubs-tests/test_compute.py @@ -241,6 +241,7 @@ def test_array_wise_functions() -> None: # Structural transforms check(pc.list_contains([[1, 2, 3]], 1), pa.BooleanArray) + check(pc.list_contains(pa.chunked_array([[[1, 2, 3]]]), 1), pa.ChunkedArray) check(pc.list_element([[1, 2, 3]], 1), pa.Int64Array) check(assert_type(pc.list_flatten([[1, 2], [3]]), pa.Array | pa.ChunkedArray), pa.Int64Array) diff --git a/python/pyarrow-stubs/compute.pyi b/python/pyarrow-stubs/compute.pyi index 894e70ccc078..ab9a97f268a2 100644 --- a/python/pyarrow-stubs/compute.pyi +++ b/python/pyarrow-stubs/compute.pyi @@ -1624,7 +1624,7 @@ def list_contains( /, *, memory_pool: MemoryPool | None = None, -) -> BooleanScalar | BooleanArray | Expression: ... +) -> BooleanScalar | BooleanArray | ChunkedArray | Expression: ... def list_element( lists: _ComputeInput, index: _ComputeInput | int, From 65ac5e3d6b5cc48c9ca7ad4db68ac5c85ba7f1cc Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Fri, 27 Nov 2026 08:39:58 +0100 Subject: [PATCH 28/33] Copilot review - list_slice update --- python/pyarrow-stubs-tests/test_compute.py | 1 + python/pyarrow-stubs/compute.pyi | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/python/pyarrow-stubs-tests/test_compute.py b/python/pyarrow-stubs-tests/test_compute.py index 649d513d8a77..ca0160d1fbeb 100644 --- a/python/pyarrow-stubs-tests/test_compute.py +++ b/python/pyarrow-stubs-tests/test_compute.py @@ -250,6 +250,7 @@ def test_array_wise_functions() -> None: check(assert_type(pc.list_parent_indices(pa.chunked_array([[[1, 2], [3]]])), pa.Int64Array | pa.ChunkedArray), pa.ChunkedArray) + check(pc.list_slice(pa.scalar([1, 2, 3]), 1), pa.ListScalar) check(pc.struct_field(pa.array([{"a": 1}]), ("a",)), pa.Array) # Replace functions always return arrays diff --git a/python/pyarrow-stubs/compute.pyi b/python/pyarrow-stubs/compute.pyi index ab9a97f268a2..dc0f690e874f 100644 --- a/python/pyarrow-stubs/compute.pyi +++ b/python/pyarrow-stubs/compute.pyi @@ -1656,7 +1656,7 @@ def list_slice( *, options: ListSliceOptions | None = None, memory_pool: MemoryPool | None = None, -) -> BaseListArray | ChunkedArray | Expression: ... +) -> _ListScalar | BaseListArray | ChunkedArray | Expression: ... def map_lookup( container: _ScalarOrArray | Expression, /, From 59936163b3d8f37406a1c93b7fd7812381d8f980 Mon Sep 17 00:00:00 2001 From: Rok Mihevc Date: Mon, 30 Nov 2026 18:25:03 +0100 Subject: [PATCH 29/33] GH-49195: [Python][Annotations] Add type stubs for I/O, IPC, and serialization formats --- python/pyarrow-stubs-tests/test_io_formats.py | 100 +++++ python/pyarrow-stubs/__init__.pyi | 42 ++ python/pyarrow-stubs/__lib/io.pyi | 391 +++++++++++++++++- python/pyarrow-stubs/__lib/ipc.pyi | 259 +++++++++++- python/pyarrow-stubs/_csv.pyi | 170 ++++++++ python/pyarrow-stubs/_feather.pyi | 47 +++ python/pyarrow-stubs/_json.pyi | 59 +++ python/pyarrow-stubs/_orc.pyi | 77 ++++ python/pyarrow-stubs/_stubs_typing.pyi | 6 + python/pyarrow-stubs/csv.pyi | 30 ++ python/pyarrow-stubs/feather.pyi | 62 +++ python/pyarrow-stubs/ipc.pyi | 113 +++++ python/pyarrow-stubs/json.pyi | 23 ++ python/pyarrow-stubs/lib.pyi | 1 + python/pyarrow-stubs/orc.pyi | 115 ++++++ 15 files changed, 1485 insertions(+), 10 deletions(-) create mode 100644 python/pyarrow-stubs-tests/test_io_formats.py create mode 100644 python/pyarrow-stubs/_csv.pyi create mode 100644 python/pyarrow-stubs/_feather.pyi create mode 100644 python/pyarrow-stubs/_json.pyi create mode 100644 python/pyarrow-stubs/_orc.pyi create mode 100644 python/pyarrow-stubs/csv.pyi create mode 100644 python/pyarrow-stubs/feather.pyi create mode 100644 python/pyarrow-stubs/ipc.pyi create mode 100644 python/pyarrow-stubs/json.pyi create mode 100644 python/pyarrow-stubs/orc.pyi diff --git a/python/pyarrow-stubs-tests/test_io_formats.py b/python/pyarrow-stubs-tests/test_io_formats.py new file mode 100644 index 000000000000..51d5357755c3 --- /dev/null +++ b/python/pyarrow-stubs-tests/test_io_formats.py @@ -0,0 +1,100 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from typing import TYPE_CHECKING + +import pyarrow as pa +import pyarrow.csv as csv +import pyarrow.feather as feather +import pyarrow.ipc as ipc +import pyarrow.json as pa_json + +from _check import assert_type, check + + +def test_io_buffers_and_streams() -> None: + buf = pa.allocate_buffer(8) + check(assert_type(buf, pa.Buffer), pa.Buffer) + check(assert_type(buf.size, int), int) + check(assert_type(buf.to_pybytes(), bytes), bytes) + check(assert_type(buf.slice(0, 4), pa.Buffer), pa.Buffer) + + rbuf = pa.allocate_buffer(8, resizable=True) + check(assert_type(rbuf, pa.ResizableBuffer), pa.ResizableBuffer) + rbuf.resize(16) + check(assert_type(buf.equals(rbuf), bool), bool) + + sink = pa.BufferOutputStream() + sink.write(b"hello") + out = sink.getvalue() + check(assert_type(out, pa.Buffer), pa.Buffer) + + reader = pa.BufferReader(out) + check(assert_type(reader.read(), bytes), bytes) + + compressed_buf = pa.compress(b"hello world", codec="gzip") + check(assert_type(compressed_buf, pa.Buffer), pa.Buffer) + compressed_bytes = pa.compress(b"hello world", codec="gzip", asbytes=True) + check(assert_type(compressed_bytes, bytes), bytes) + decompressed = pa.decompress( + compressed_bytes, decompressed_size=11, codec="gzip", asbytes=True + ) + check(assert_type(decompressed, bytes), bytes) + + +def test_ipc() -> None: + batch = pa.record_batch([pa.array([1, 2])], names=["a"]) + sink = pa.BufferOutputStream() + opts = ipc.IpcWriteOptions(compression="zstd") + with ipc.new_stream(sink, batch.schema, options=opts) as writer: + writer.write_batch(batch) + buf = sink.getvalue() + + with ipc.open_stream(buf) as reader: + check(assert_type(reader.schema, pa.Schema), pa.Schema) + table = reader.read_all() + check(assert_type(table, pa.Table), pa.Table) + + +def test_csv_and_json() -> None: + read_opts = csv.ReadOptions(use_threads=False) + parse_opts = csv.ParseOptions(delimiter=",") + convert_opts = csv.ConvertOptions(check_utf8=True) + table = csv.read_csv( + pa.BufferReader(b"a,b\n1,2\n"), + read_options=read_opts, + parse_options=parse_opts, + convert_options=convert_opts, + ) + check(assert_type(table, pa.Table), pa.Table) + + jtable = pa_json.read_json(pa.BufferReader(b'{"a": 1}\n{"a": 2}\n')) + check(assert_type(jtable, pa.Table), pa.Table) + + +def test_feather() -> None: + table = pa.table({"a": [1, 2]}) + sink = pa.BufferOutputStream() + feather.write_feather(table, sink) + read_back = feather.read_table(pa.BufferReader(sink.getvalue())) + check(assert_type(read_back, pa.Table), pa.Table) + + +def test_invalid_usage() -> None: + if TYPE_CHECKING: + pa.allocate_buffer("not an int") # type: ignore[call-overload] # ty: ignore[no-matching-overload] + pa.compress(b"abc", codec="invalid") # type: ignore[call-overload] # ty: ignore[no-matching-overload] diff --git a/python/pyarrow-stubs/__init__.pyi b/python/pyarrow-stubs/__init__.pyi index d0f4f25f6cf1..60b52f4a5a77 100644 --- a/python/pyarrow-stubs/__init__.pyi +++ b/python/pyarrow-stubs/__init__.pyi @@ -43,8 +43,17 @@ from pyarrow.lib import ( Bool8Type as Bool8Type, BooleanArray as BooleanArray, BooleanScalar as BooleanScalar, + Buffer as Buffer, + BufferOutputStream as BufferOutputStream, + BufferReader as BufferReader, + BufferedInputStream as BufferedInputStream, + BufferedOutputStream as BufferedOutputStream, BuildInfo as BuildInfo, + CacheOptions as CacheOptions, ChunkedArray as ChunkedArray, + Codec as Codec, + CompressedInputStream as CompressedInputStream, + CompressedOutputStream as CompressedOutputStream, CppBuildInfo as CppBuildInfo, DataType as DataType, Date32Array as Date32Array, @@ -85,6 +94,7 @@ from pyarrow.lib import ( FixedSizeBinaryArray as FixedSizeBinaryArray, FixedSizeBinaryScalar as FixedSizeBinaryScalar, FixedSizeBinaryType as FixedSizeBinaryType, + FixedSizeBufferWriter as FixedSizeBufferWriter, FixedSizeListArray as FixedSizeListArray, FixedSizeListScalar as FixedSizeListScalar, FixedSizeListType as FixedSizeListType, @@ -127,19 +137,26 @@ from pyarrow.lib import ( MapScalar as MapScalar, MapType as MapType, MemoryManager as MemoryManager, + MemoryMappedFile as MemoryMappedFile, MemoryPool as MemoryPool, + MockOutputStream as MockOutputStream, MonthDayNano as MonthDayNano, MonthDayNanoIntervalArray as MonthDayNanoIntervalArray, MonthDayNanoIntervalScalar as MonthDayNanoIntervalScalar, NA as NA, + NativeFile as NativeFile, NullArray as NullArray, NullScalar as NullScalar, NumericArray as NumericArray, + OSFile as OSFile, OpaqueArray as OpaqueArray, OpaqueScalar as OpaqueScalar, OpaqueType as OpaqueType, ProxyMemoryPool as ProxyMemoryPool, + PythonFile as PythonFile, RecordBatch as RecordBatch, + RecordBatchReader as RecordBatchReader, + ResizableBuffer as ResizableBuffer, RunEndEncodedArray as RunEndEncodedArray, RunEndEncodedScalar as RunEndEncodedScalar, RunEndEncodedType as RunEndEncodedType, @@ -170,6 +187,7 @@ from pyarrow.lib import ( TimestampArray as TimestampArray, TimestampScalar as TimestampScalar, TimestampType as TimestampType, + TransformInputStream as TransformInputStream, UInt16Array as UInt16Array, UInt16Scalar as UInt16Scalar, UInt32Array as UInt32Array, @@ -186,6 +204,7 @@ from pyarrow.lib import ( UuidScalar as UuidScalar, UuidType as UuidType, VersionInfo as VersionInfo, + allocate_buffer as allocate_buffer, array as array, binary as binary, binary_view as binary_view, @@ -193,18 +212,21 @@ from pyarrow.lib import ( bool_ as bool_, build_info as build_info, chunked_array as chunked_array, + compress as compress, concat_arrays as concat_arrays, concat_batches as concat_batches, concat_tables as concat_tables, cpp_build_info as cpp_build_info, cpp_version as cpp_version, cpp_version_info as cpp_version_info, + create_memory_map as create_memory_map, date32 as date32, date64 as date64, decimal128 as decimal128, decimal256 as decimal256, decimal32 as decimal32, decimal64 as decimal64, + decompress as decompress, default_cpu_memory_manager as default_cpu_memory_manager, default_memory_pool as default_memory_pool, dense_union as dense_union, @@ -216,12 +238,15 @@ from pyarrow.lib import ( float16 as float16, float32 as float32, float64 as float64, + foreign_buffer as foreign_buffer, from_numpy_dtype as from_numpy_dtype, infer_type as infer_type, + input_stream as input_stream, int16 as int16, int32 as int32, int64 as int64, int8 as int8, + io_thread_count as io_thread_count, jemalloc_memory_pool as jemalloc_memory_pool, jemalloc_set_decay_ms as jemalloc_set_decay_ms, json_ as json_, @@ -235,12 +260,15 @@ from pyarrow.lib import ( log_memory_allocations as log_memory_allocations, logging_memory_pool as logging_memory_pool, map_ as map_, + memory_map as memory_map, mimalloc_memory_pool as mimalloc_memory_pool, month_day_nano_interval as month_day_nano_interval, null as null, nulls as nulls, opaque as opaque, + output_stream as output_stream, proxy_memory_pool as proxy_memory_pool, + py_buffer as py_buffer, record_batch as record_batch, register_extension_type as register_extension_type, repeat as repeat, @@ -248,6 +276,7 @@ from pyarrow.lib import ( runtime_info as runtime_info, scalar as scalar, schema as schema, + set_io_thread_count as set_io_thread_count, set_memory_pool as set_memory_pool, set_timezone_db_path as set_timezone_db_path, sparse_union as sparse_union, @@ -261,6 +290,7 @@ from pyarrow.lib import ( time64 as time64, timestamp as timestamp, total_allocated_bytes as total_allocated_bytes, + transcoding_input_stream as transcoding_input_stream, type_for_alias as type_for_alias, uint16 as uint16, uint32 as uint32, @@ -273,7 +303,19 @@ from pyarrow.lib import ( uuid as uuid, ) +from pyarrow import ipc as ipc from pyarrow import types as types +from pyarrow.ipc import ( + Message as Message, + MessageReader as MessageReader, + MetadataVersion as MetadataVersion, + RecordBatchFileReader as RecordBatchFileReader, + RecordBatchFileWriter as RecordBatchFileWriter, + RecordBatchStreamReader as RecordBatchStreamReader, + RecordBatchStreamWriter as RecordBatchStreamWriter, + deserialize_pandas as deserialize_pandas, + serialize_pandas as serialize_pandas, +) # pyarrow/__init__.py imports pyarrow.lib._NULL as NULL NULL: NullScalar diff --git a/python/pyarrow-stubs/__lib/io.pyi b/python/pyarrow-stubs/__lib/io.pyi index 8a1da39a1cf2..1628b781e2c5 100644 --- a/python/pyarrow-stubs/__lib/io.pyi +++ b/python/pyarrow-stubs/__lib/io.pyi @@ -15,11 +15,392 @@ # specific language governing permissions and limitations # under the License. -# Placeholder stub - complete annotations in future PR. -# At runtime, these symbols are provided by the pyarrow.lib C extension. +import builtins +from collections.abc import Callable, Iterable +from io import IOBase +from typing import Any, Literal, Self, SupportsIndex, TypeAlias, overload -from typing import Any +from _typeshed import StrPath +from pyarrow._stubs_typing import Compression, SupportPyBuffer +from pyarrow.lib import ( + Device, + DeviceAllocationType, + KeyValueMetadata, + MemoryManager, + MemoryPool, + _Weakrefable, +) -class Buffer: ... +def have_libhdfs() -> bool: ... +def io_thread_count() -> int: ... +def set_io_thread_count(count: int) -> None: ... -def __getattr__(name: str) -> Any: ... +_Mode: TypeAlias = Literal["rb", "wb", "rb+", "ab"] + +class NativeFile(_Weakrefable): + _default_chunk_size: int + + def __enter__(self) -> Self: ... + def __exit__(self, exc_type: object, exc_value: object, tb: object) -> None: ... + @property + def mode(self) -> _Mode: ... + def readable(self) -> bool: ... + def writable(self) -> bool: ... + def seekable(self) -> bool: ... + def isatty(self) -> bool: ... + def fileno(self) -> int: ... + @property + def closed(self) -> bool: ... + def close(self) -> None: ... + def size(self) -> int: ... + def metadata(self) -> KeyValueMetadata: ... + def tell(self) -> int: ... + def seek(self, position: int, whence: int = 0) -> int: ... + def flush(self) -> None: ... + def write(self, data: bytes | SupportPyBuffer) -> int: ... + def read(self, nbytes: int | None = None) -> bytes: ... + def get_stream(self, file_offset: int, nbytes: int) -> NativeFile: ... + def read_at(self, nbytes: int, offset: int) -> bytes: ... + def read1(self, nbytes: int | None = None) -> bytes: ... + def readall(self) -> bytes: ... + def readinto(self, b: SupportPyBuffer) -> int: ... + def readline(self, size: int | None = None) -> bytes: ... + def readlines(self, hint: int | None = None) -> list[bytes]: ... + def __iter__(self) -> Self: ... + def __next__(self) -> bytes: ... + def read_buffer(self, nbytes: int | None = None) -> Buffer: ... + def truncate(self) -> None: ... + def writelines(self, lines: Iterable[bytes]) -> None: ... + def download( + self, stream_or_path: StrPath | IOBase, buffer_size: int | None = None + ) -> None: ... + def upload(self, stream: IOBase, buffer_size: int | None = None) -> None: ... + +# ---------------------------------------------------------------------- +# Python file-like objects + +class PythonFile(NativeFile): + def __init__( + self, handle: IOBase, mode: Literal["r", "w"] | None = None + ) -> None: ... + def truncate(self, pos: int | None = None) -> None: ... + +class MemoryMappedFile(NativeFile): + @staticmethod + def create(path: str, size: int) -> MemoryMappedFile: ... + def _open( + self, path: str, mode: Literal["r", "rb", "w", "wb", "r+", "r+b", "rb+"] = "r" + ) -> None: ... + def resize(self, new_size: int) -> None: ... + +def memory_map( + path: str, mode: Literal["r", "rb", "w", "wb", "r+", "r+b", "rb+"] = "r" +) -> MemoryMappedFile: ... + +create_memory_map = MemoryMappedFile.create + +class OSFile(NativeFile): + def __init__( + self, + path: str, + mode: Literal["r", "rb", "w", "wb", "a", "ab"], + memory_pool: MemoryPool | None = None, + ) -> None: ... + +class FixedSizeBufferWriter(NativeFile): + def __init__(self, buffer: Buffer) -> None: ... + def set_memcopy_threads(self, num_threads: int) -> None: ... + def set_memcopy_blocksize(self, blocksize: int) -> None: ... + def set_memcopy_threshold(self, threshold: int) -> None: ... + +# ---------------------------------------------------------------------- +# Arrow buffers + +class Buffer(_Weakrefable): + def __len__(self) -> int: ... + def _assert_cpu(self) -> None: ... + @property + def size(self) -> int: ... + @property + def address(self) -> int: ... + def hex(self) -> bytes: ... + @property + def is_mutable(self) -> bool: ... + @property + def is_cpu(self) -> bool: ... + @property + def device(self) -> Device: ... + @property + def memory_manager(self) -> MemoryManager: ... + @property + def device_type(self) -> DeviceAllocationType: ... + @property + def parent(self) -> Buffer | None: ... + @overload + def __getitem__(self, key: builtins.slice, /) -> Self: ... + @overload + def __getitem__(self, key: int, /) -> int: ... + def slice(self, offset: int = 0, length: int | None = None) -> Self: ... + def equals(self, other: Buffer) -> bool: ... + def __reduce_ex__(self, protocol: SupportsIndex) -> str | tuple[Any, ...]: ... + def to_pybytes(self) -> bytes: ... + def __buffer__(self, flags: int, /) -> memoryview: ... + +class ResizableBuffer(Buffer): + def resize(self, new_size: int, shrink_to_fit: bool = False) -> None: ... + +@overload +def allocate_buffer( + size: int, memory_pool: MemoryPool | None = None, resizable: Literal[False] = False +) -> Buffer: ... +@overload +def allocate_buffer( + size: int, memory_pool: MemoryPool | None = None, *, resizable: Literal[True] +) -> ResizableBuffer: ... +@overload +def allocate_buffer( + size: int, memory_pool: MemoryPool | None, resizable: Literal[True] +) -> ResizableBuffer: ... +@overload +def allocate_buffer( + size: int, memory_pool: MemoryPool | None = None, resizable: bool = False +) -> Buffer: ... + +# ---------------------------------------------------------------------- +# Arrow Stream +class BufferOutputStream(NativeFile): + def __init__(self, memory_pool: MemoryPool | None = None) -> None: ... + def getvalue(self) -> Buffer: ... + +class MockOutputStream(NativeFile): ... + +class BufferReader(NativeFile): + def __init__(self, obj: Buffer | bytes | SupportPyBuffer) -> None: ... + +class CompressedInputStream(NativeFile): + def __init__( + self, + stream: StrPath | NativeFile | IOBase, + compression: Literal["bz2", "brotli", "gzip", "lz4", "zstd"], + ) -> None: ... + +class CompressedOutputStream(NativeFile): + def __init__( + self, + stream: StrPath | NativeFile | IOBase, + compression: Literal["bz2", "brotli", "gzip", "lz4", "zstd"], + ) -> None: ... + +class BufferedInputStream(NativeFile): + def __init__( + self, + stream: NativeFile, + buffer_size: int, + memory_pool: MemoryPool | None = None, + ) -> None: ... + def detach(self) -> NativeFile: ... + +class BufferedOutputStream(NativeFile): + def __init__( + self, + stream: NativeFile, + buffer_size: int, + memory_pool: MemoryPool | None = None, + ) -> None: ... + def detach(self) -> NativeFile: ... + +class TransformInputStream(NativeFile): + def __init__( + self, stream: NativeFile, transform_func: Callable[[Buffer], Any] + ) -> None: ... + +class Transcoder: + def __init__(self, decoder: Any, encoder: Any) -> None: ... + def __call__(self, buf: Buffer) -> bytes: ... + +def transcoding_input_stream( + stream: NativeFile, src_encoding: str, dest_encoding: str +) -> TransformInputStream: ... +def py_buffer(obj: SupportPyBuffer) -> Buffer: ... +def foreign_buffer(address: int, size: int, base: Any | None = None) -> Buffer: ... +def as_buffer(o: Buffer | SupportPyBuffer) -> Buffer: ... + +# --------------------------------------------------------------------- + +class CacheOptions(_Weakrefable): + hole_size_limit: int + range_size_limit: int + lazy: bool + prefetch_limit: int + def __init__( + self, + *, + hole_size_limit: int | None = None, + range_size_limit: int | None = None, + lazy: bool = True, + prefetch_limit: int = 0, + ) -> None: ... + @staticmethod + def from_network_metrics( + time_to_first_byte_millis: int, + transfer_bandwidth_mib_per_sec: int, + ideal_bandwidth_utilization_frac: float = 0.9, + max_ideal_request_size_mib: int = 64, + ) -> CacheOptions: ... + +class Codec(_Weakrefable): + def __init__( + self, compression: Compression, compression_level: int | None = None + ) -> None: ... + @staticmethod + def detect(path: StrPath) -> Codec: ... + @staticmethod + def is_available(compression: Compression) -> bool: ... + @staticmethod + def supports_compression_level(compression: Compression) -> int: ... + @staticmethod + def default_compression_level(compression: Compression) -> int: ... + @staticmethod + def minimum_compression_level(compression: Compression) -> int: ... + @staticmethod + def maximum_compression_level(compression: Compression) -> int: ... + @property + def name(self) -> Compression: ... + @property + def compression_level(self) -> int: ... + @overload + def compress( + self, + buf: Buffer | bytes | SupportPyBuffer, + asbytes: Literal[False] = False, + memory_pool: MemoryPool | None = None, + ) -> Buffer: ... + @overload + def compress( + self, + buf: Buffer | bytes | SupportPyBuffer, + asbytes: Literal[True], + memory_pool: MemoryPool | None = None, + ) -> bytes: ... + @overload + def compress( + self, + buf: Buffer | bytes | SupportPyBuffer, + asbytes: bool = False, + memory_pool: MemoryPool | None = None, + ) -> Buffer | bytes: ... + @overload + def decompress( + self, + buf: Buffer | bytes | SupportPyBuffer, + decompressed_size: int | None = None, + asbytes: Literal[False] = False, + memory_pool: MemoryPool | None = None, + ) -> Buffer: ... + @overload + def decompress( + self, + buf: Buffer | bytes | SupportPyBuffer, + decompressed_size: int | None = None, + asbytes: Literal[True] = ..., + memory_pool: MemoryPool | None = None, + ) -> bytes: ... + @overload + def decompress( + self, + buf: Buffer | bytes | SupportPyBuffer, + decompressed_size: int | None = None, + asbytes: bool = False, + memory_pool: MemoryPool | None = None, + ) -> Buffer | bytes: ... + +@overload +def compress( + buf: Buffer | bytes | SupportPyBuffer, + codec: Compression = "lz4", + asbytes: Literal[False] = False, + memory_pool: MemoryPool | None = None, +) -> Buffer: ... +@overload +def compress( + buf: Buffer | bytes | SupportPyBuffer, + codec: Compression = "lz4", + asbytes: Literal[True] = ..., + memory_pool: MemoryPool | None = None, +) -> bytes: ... +@overload +def compress( + buf: Buffer | bytes | SupportPyBuffer, + codec: Compression = "lz4", + asbytes: bool = False, + memory_pool: MemoryPool | None = None, +) -> Buffer | bytes: ... +@overload +def decompress( + buf: Buffer | bytes | SupportPyBuffer, + decompressed_size: int | None = None, + codec: Compression = "lz4", + asbytes: Literal[False] = False, + memory_pool: MemoryPool | None = None, +) -> Buffer: ... +@overload +def decompress( + buf: Buffer | bytes | SupportPyBuffer, + decompressed_size: int | None = None, + codec: Compression = "lz4", + asbytes: Literal[True] = ..., + memory_pool: MemoryPool | None = None, +) -> bytes: ... +@overload +def decompress( + buf: Buffer | bytes | SupportPyBuffer, + decompressed_size: int | None = None, + codec: Compression = "lz4", + asbytes: bool = False, + memory_pool: MemoryPool | None = None, +) -> Buffer | bytes: ... +def input_stream( + source: StrPath | Buffer | IOBase, + compression: Literal["detect", "bz2", "brotli", "gzip", "lz4", "zstd"] = "detect", + buffer_size: int | None = None, +) -> BufferReader: ... +def output_stream( + source: StrPath | Buffer | IOBase, + compression: Literal["detect", "bz2", "brotli", "gzip", "lz4", "zstd"] = "detect", + buffer_size: int | None = None, +) -> NativeFile: ... + +__all__ = [ + "have_libhdfs", + "io_thread_count", + "set_io_thread_count", + "NativeFile", + "PythonFile", + "MemoryMappedFile", + "memory_map", + "create_memory_map", + "OSFile", + "FixedSizeBufferWriter", + "Buffer", + "ResizableBuffer", + "allocate_buffer", + "BufferOutputStream", + "MockOutputStream", + "BufferReader", + "CompressedInputStream", + "CompressedOutputStream", + "BufferedInputStream", + "BufferedOutputStream", + "TransformInputStream", + "Transcoder", + "transcoding_input_stream", + "py_buffer", + "foreign_buffer", + "as_buffer", + "CacheOptions", + "Codec", + "compress", + "decompress", + "input_stream", + "output_stream", +] diff --git a/python/pyarrow-stubs/__lib/ipc.pyi b/python/pyarrow-stubs/__lib/ipc.pyi index c84964043e4a..4c8f6b3c4465 100644 --- a/python/pyarrow-stubs/__lib/ipc.pyi +++ b/python/pyarrow-stubs/__lib/ipc.pyi @@ -15,11 +15,260 @@ # specific language governing permissions and limitations # under the License. -# Placeholder stub - complete annotations in future PR. -# At runtime, these symbols are provided by the pyarrow.lib C extension. +import enum +from collections.abc import Iterable, Iterator, Mapping +from io import IOBase +from typing import Any, Literal, NamedTuple, Self -from typing import Any, TypeAlias +import pandas as pd +from pyarrow._stubs_typing import SupportPyBuffer +from pyarrow.lib import ( + Buffer, + BufferReader, + Codec, + DictionaryMemo, + KeyValueMetadata, + MemoryPool, + NativeFile, + RecordBatch, + Schema, + Table, + Tensor, + _Weakrefable, +) +from typing_extensions import CapsuleType -RecordBatchReader: TypeAlias = Any +class MetadataVersion(enum.IntEnum): + V1 = 0 + V2 = 1 + V3 = 2 + V4 = 3 + V5 = 4 -def __getattr__(name: str) -> Any: ... +class Alignment(enum.IntEnum): + Any = 0 + At64Byte = 64 + DataTypeSpecific = -3 + +class WriteStats(NamedTuple): + num_messages: int + num_record_batches: int + num_dictionary_batches: int + num_dictionary_deltas: int + num_replaced_dictionaries: int + +class ReadStats(NamedTuple): + num_messages: int + num_record_batches: int + num_dictionary_batches: int + num_dictionary_deltas: int + num_replaced_dictionaries: int + +class IpcReadOptions(_Weakrefable): + ensure_native_endian: bool + use_threads: bool + ensure_alignment: Alignment + included_fields: list[int] | None + + def __init__( + self, + *, + ensure_native_endian: bool = True, + use_threads: bool = True, + ensure_alignment: Alignment = ..., + included_fields: list[int] | None = None, + ) -> None: ... + +class IpcWriteOptions(_Weakrefable): + metadata_version: Any + allow_64bit: bool + use_legacy_format: bool + compression: Any + use_threads: bool + emit_dictionary_deltas: bool + unify_dictionaries: bool + + def __init__( + self, + *, + metadata_version: MetadataVersion = ..., + allow_64bit: bool = False, + use_legacy_format: bool = False, + compression: Codec | Literal["lz4", "zstd"] | None = None, + use_threads: bool = True, + emit_dictionary_deltas: bool = False, + unify_dictionaries: bool = False, + ) -> None: ... + +class Message(_Weakrefable): + @property + def type(self) -> str: ... + @property + def metadata(self) -> Buffer: ... + @property + def metadata_version(self) -> MetadataVersion: ... + @property + def body(self) -> Buffer | None: ... + def equals(self, other: Message) -> bool: ... + def serialize_to( + self, + sink: NativeFile, + alignment: int = 8, + memory_pool: MemoryPool | None = None, + ) -> None: ... + def serialize( + self, alignment: int = 8, memory_pool: MemoryPool | None = None + ) -> Buffer: ... + +class MessageReader(_Weakrefable): + @staticmethod + def open_stream( + source: bytes | NativeFile | IOBase | SupportPyBuffer, + ) -> MessageReader: ... + def __iter__(self) -> Self: ... + def read_next_message(self) -> Message: ... + + __next__ = read_next_message + +# ---------------------------------------------------------------------- +# File and stream readers and writers + +class _CRecordBatchWriter(_Weakrefable): + def write(self, table_or_batch: Table | RecordBatch) -> None: ... + def write_batch( + self, + batch: RecordBatch, + custom_metadata: Mapping[bytes, bytes] | KeyValueMetadata | None = None, + ) -> None: ... + def write_table(self, table: Table, max_chunksize: int | None = None) -> None: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, exc_type: object, exc_val: object, exc_tb: object) -> None: ... + @property + def stats(self) -> WriteStats: ... + +class _RecordBatchStreamWriter(_CRecordBatchWriter): + @property + def _use_legacy_format(self) -> bool: ... + @property + def _metadata_version(self) -> MetadataVersion: ... + def _open( + self, + sink: Any, + schema: Schema, + options: IpcWriteOptions = ..., + ) -> None: ... + +class _ReadPandasMixin: + def read_pandas(self, **options: Any) -> pd.DataFrame: ... + +class RecordBatchReader(_ReadPandasMixin, _Weakrefable): + def __iter__(self) -> Self: ... + def read_next_batch(self) -> RecordBatch: ... + + __next__ = read_next_batch + @property + def schema(self) -> Schema: ... + def read_next_batch_with_custom_metadata(self) -> RecordBatchWithMetadata: ... + def iter_batches_with_custom_metadata( + self, + ) -> Iterator[RecordBatchWithMetadata]: ... + def read_all(self) -> Table: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, exc_type: object, exc_val: object, exc_tb: object) -> None: ... + def cast(self, target_schema: Schema) -> Self: ... + def _export_to_c(self, out_ptr: int) -> None: ... + @staticmethod + def _import_from_c(in_ptr: int) -> RecordBatchReader: ... + def __arrow_c_stream__( + self, requested_schema: CapsuleType | None = None + ) -> CapsuleType: ... + @staticmethod + def _import_from_c_capsule(stream: CapsuleType) -> RecordBatchReader: ... + @staticmethod + def from_stream(data: Any, schema: Schema | None = None) -> RecordBatchReader: ... + @staticmethod + def from_batches( + schema: Schema, batches: Iterable[RecordBatch] + ) -> RecordBatchReader: ... + +class _RecordBatchStreamReader(RecordBatchReader): + @property + def stats(self) -> ReadStats: ... + def _open( + self, + source: Any, + options: IpcReadOptions | None = ..., + memory_pool: MemoryPool | None = None, + ) -> Self: ... + +class _RecordBatchFileWriter(_RecordBatchStreamWriter): ... + +class RecordBatchWithMetadata(NamedTuple): + batch: RecordBatch + custom_metadata: KeyValueMetadata + +class _RecordBatchFileReader(_ReadPandasMixin, _Weakrefable): + @property + def num_record_batches(self) -> int: ... + def get_batch(self, i: int) -> RecordBatch: ... + + get_record_batch = get_batch + def get_batch_with_custom_metadata(self, i: int) -> RecordBatchWithMetadata: ... + def read_all(self) -> Table: ... + def __enter__(self) -> Self: ... + def __exit__(self, exc_type: object, exc_val: object, exc_tb: object) -> None: ... + @property + def schema(self) -> Schema: ... + @property + def stats(self) -> ReadStats: ... + @property + def metadata(self) -> KeyValueMetadata | None: ... + def _open( + self, + source: Any, + footer_offset: int | None = None, + options: IpcReadOptions | None = ..., + memory_pool: MemoryPool | None = None, + ) -> Self: ... + +def get_tensor_size(tensor: Tensor) -> int: ... +def get_record_batch_size(batch: RecordBatch) -> int: ... +def write_tensor(tensor: Tensor, dest: NativeFile) -> int: ... +def read_tensor(source: NativeFile) -> Tensor: ... +def read_message(source: NativeFile | IOBase | SupportPyBuffer) -> Message: ... +def read_schema( + obj: Buffer | Message | BufferReader, dictionary_memo: DictionaryMemo | None = None +) -> Schema: ... +def read_record_batch( + obj: Message | SupportPyBuffer, + schema: Schema, + dictionary_memo: DictionaryMemo | None = None, +) -> RecordBatch: ... + +__all__ = [ + "MetadataVersion", + "Alignment", + "WriteStats", + "ReadStats", + "IpcReadOptions", + "IpcWriteOptions", + "Message", + "MessageReader", + "_CRecordBatchWriter", + "_RecordBatchStreamWriter", + "_ReadPandasMixin", + "RecordBatchReader", + "_RecordBatchStreamReader", + "_RecordBatchFileWriter", + "RecordBatchWithMetadata", + "_RecordBatchFileReader", + "get_tensor_size", + "get_record_batch_size", + "write_tensor", + "read_tensor", + "read_message", + "read_schema", + "read_record_batch", +] diff --git a/python/pyarrow-stubs/_csv.pyi b/python/pyarrow-stubs/_csv.pyi new file mode 100644 index 000000000000..a6f293386346 --- /dev/null +++ b/python/pyarrow-stubs/_csv.pyi @@ -0,0 +1,170 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from collections.abc import Callable, Sequence +from typing import IO, Any, Literal, NamedTuple + +from _typeshed import StrPath + +from . import lib + +class ReadOptions(lib._Weakrefable): + use_threads: bool + block_size: int | None + skip_rows: int + skip_rows_after_names: int + column_names: Sequence[str] | None + autogenerate_column_names: bool + encoding: str + + def __init__( + self, + use_threads: bool | None = None, + *, + block_size: int | None = None, + skip_rows: int | None = None, + skip_rows_after_names: int | None = None, + column_names: Sequence[str] | None = None, + autogenerate_column_names: bool | None = None, + encoding: str = "utf8", + ) -> None: ... + def equals(self, other: ReadOptions) -> bool: ... + def validate(self) -> None: ... + +class ParseOptions(lib._Weakrefable): + delimiter: str + quote_char: str | Literal[False] + double_quote: bool + escape_char: str | Literal[False] + newlines_in_values: bool + ignore_empty_lines: bool + invalid_row_handler: Callable[[InvalidRow], str] | None + + def __init__( + self, + delimiter: str | None = None, + *, + quote_char: str | Literal[False] | None = None, + double_quote: bool | None = None, + escape_char: str | Literal[False] | None = None, + newlines_in_values: bool | None = None, + ignore_empty_lines: bool | None = None, + invalid_row_handler: Callable[[InvalidRow], str] | None = None, + ) -> None: ... + def equals(self, other: ParseOptions) -> bool: ... + def validate(self) -> None: ... + +class ConvertOptions(lib._Weakrefable): + check_utf8: bool + column_types: ( + lib.Schema | dict[str, lib.DataType] | Sequence[tuple[str, lib.DataType]] | None + ) + null_values: list[str] | None + true_values: list[str] | None + false_values: list[str] | None + decimal_point: str + strings_can_be_null: bool + quoted_strings_can_be_null: bool + include_columns: list[str] | None + include_missing_columns: bool + auto_dict_encode: bool + auto_dict_max_cardinality: int | None + timestamp_parsers: Sequence[str | lib._Weakrefable] | None + + def __init__( + self, + check_utf8: bool | None = None, + *, + column_types: ( + lib.Schema + | dict[str, lib.DataType] + | Sequence[tuple[str, lib.DataType]] + | None + ) = None, + null_values: Sequence[str] | None = None, + true_values: Sequence[str] | None = None, + false_values: Sequence[str] | None = None, + decimal_point: str | None = None, + strings_can_be_null: bool | None = None, + quoted_strings_can_be_null: bool | None = None, + include_columns: Sequence[str] | None = None, + include_missing_columns: bool | None = None, + auto_dict_encode: bool | None = None, + auto_dict_max_cardinality: int | None = None, + timestamp_parsers: Sequence[str | lib._Weakrefable] | None = None, + ) -> None: ... + def equals(self, other: ConvertOptions) -> bool: ... + def validate(self) -> None: ... + +class WriteOptions(lib._Weakrefable): + include_header: bool + batch_size: int + delimiter: str + quoting_style: Literal["needed", "all_valid", "none"] + quoting_header: Literal["needed", "all_valid", "none"] + + def __init__( + self, + include_header: bool = True, + *, + batch_size: int = 1024, + delimiter: str = ",", + quoting_style: Literal["needed", "all_valid", "none"] = "needed", + quoting_header: Literal["needed", "all_valid", "none"] = "needed", + ) -> None: ... + def validate(self) -> None: ... + +class InvalidRow(NamedTuple): + expected_columns: int + actual_columns: int + number: int | None + text: str + +class CSVWriter(lib._CRecordBatchWriter): + def __init__( + self, + sink: StrPath | lib.NativeFile | IO[Any], + schema: lib.Schema, + write_options: WriteOptions | None = None, + *, + memory_pool: lib.MemoryPool | None = None, + ) -> None: ... + +class CSVStreamingReader(lib.RecordBatchReader): ... + +ISO8601: lib._Weakrefable + +def open_csv( + input_file: StrPath | lib.NativeFile | IO[Any], + read_options: ReadOptions | None = None, + parse_options: ParseOptions | None = None, + convert_options: ConvertOptions | None = None, + memory_pool: lib.MemoryPool | None = None, +) -> CSVStreamingReader: ... +def read_csv( + input_file: StrPath | lib.NativeFile | IO[Any], + read_options: ReadOptions | None = None, + parse_options: ParseOptions | None = None, + convert_options: ConvertOptions | None = None, + memory_pool: lib.MemoryPool | None = None, +) -> lib.Table: ... +def write_csv( + data: lib.RecordBatch | lib.Table, + output_file: StrPath | lib.NativeFile | IO[Any], + write_options: WriteOptions | None = None, + memory_pool: lib.MemoryPool | None = None, +) -> None: ... diff --git a/python/pyarrow-stubs/_feather.pyi b/python/pyarrow-stubs/_feather.pyi new file mode 100644 index 000000000000..ebc922ae0843 --- /dev/null +++ b/python/pyarrow-stubs/_feather.pyi @@ -0,0 +1,47 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from collections.abc import Sequence +from typing import IO, Any, Literal, Self + +from _typeshed import StrPath + +from .lib import Buffer, NativeFile, Table, _Weakrefable + +class FeatherError(Exception): ... + +def write_feather( + table: Table, + dest: StrPath | IO[Any] | NativeFile, + compression: str | None = None, + compression_level: int | None = None, + chunksize: int | None = None, + version: Literal[1, 2] = 2, +) -> None: ... + +class FeatherReader(_Weakrefable): + def __new__( + cls, + source: StrPath | IO[Any] | NativeFile | Buffer, + use_memory_map: bool = True, + use_threads: bool = True, + ) -> Self: ... + @property + def version(self) -> str: ... + def read(self) -> Table: ... + def read_indices(self, indices: Sequence[int]) -> Table: ... + def read_names(self, names: Sequence[str]) -> Table: ... diff --git a/python/pyarrow-stubs/_json.pyi b/python/pyarrow-stubs/_json.pyi new file mode 100644 index 000000000000..042c18d59381 --- /dev/null +++ b/python/pyarrow-stubs/_json.pyi @@ -0,0 +1,59 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from typing import IO, Any, Literal + +from _typeshed import StrPath + +from .lib import MemoryPool, NativeFile, RecordBatchReader, Schema, Table, _Weakrefable + +class ReadOptions(_Weakrefable): + use_threads: bool + block_size: int + + def __init__( + self, use_threads: bool | None = None, block_size: int | None = None + ) -> None: ... + def equals(self, other: ReadOptions) -> bool: ... + +class ParseOptions(_Weakrefable): + explicit_schema: Schema + newlines_in_values: bool + unexpected_field_behavior: Literal["ignore", "error", "infer"] + + def __init__( + self, + explicit_schema: Schema | None = None, + newlines_in_values: bool | None = None, + unexpected_field_behavior: Literal["ignore", "error", "infer"] = "infer", + ) -> None: ... + def equals(self, other: ParseOptions) -> bool: ... + +class JSONStreamingReader(RecordBatchReader): ... + +def read_json( + input_file: StrPath | NativeFile | IO[Any], + read_options: ReadOptions | None = None, + parse_options: ParseOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> Table: ... +def open_json( + input_file: StrPath | NativeFile | IO[Any], + read_options: ReadOptions | None = None, + parse_options: ParseOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> JSONStreamingReader: ... diff --git a/python/pyarrow-stubs/_orc.pyi b/python/pyarrow-stubs/_orc.pyi new file mode 100644 index 000000000000..63dd07c7e7ab --- /dev/null +++ b/python/pyarrow-stubs/_orc.pyi @@ -0,0 +1,77 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from typing import IO, Any, Literal, Self + +from .lib import ( + Buffer, + KeyValueMetadata, + MemoryPool, + NativeFile, + RecordBatch, + Schema, + Table, + _Weakrefable, +) + +class ORCReader(_Weakrefable): + def __new__(cls, memory_pool: MemoryPool | None = None) -> Self: ... + def open( + self, source: str | NativeFile | Buffer, use_memory_map: bool = True + ) -> None: ... + def metadata(self) -> KeyValueMetadata: ... + def schema(self) -> Schema: ... + def nrows(self) -> int: ... + def nstripes(self) -> int: ... + def file_version(self) -> str: ... + def software_version(self) -> str: ... + def compression( + self, + ) -> Literal["UNCOMPRESSED", "ZLIB", "SNAPPY", "LZ4", "ZSTD"]: ... + def compression_size(self) -> int: ... + def row_index_stride(self) -> int: ... + def writer(self) -> str: ... + def writer_version(self) -> str: ... + def nstripe_statistics(self) -> int: ... + def content_length(self) -> int: ... + def stripe_statistics_length(self) -> int: ... + def file_footer_length(self) -> int: ... + def file_postscript_length(self) -> int: ... + def file_length(self) -> int: ... + def serialized_file_tail(self) -> int: ... + def read_stripe(self, n: int, columns: list[str] | None = None) -> RecordBatch: ... + def read(self, columns: list[str] | None = None) -> Table: ... + +class ORCWriter(_Weakrefable): + def open( + self, + where: str | NativeFile | IO[Any], + *, + file_version: str | None = None, + batch_size: int | None = None, + stripe_size: int | None = None, + compression: Any = None, + compression_block_size: int | None = None, + compression_strategy: Any = None, + row_index_stride: int | None = None, + padding_tolerance: float | None = None, + dictionary_key_size_threshold: float | None = None, + bloom_filter_columns: list[int] | None = None, + bloom_filter_fpp: float | None = None, + ) -> None: ... + def write(self, table: Table) -> None: ... + def close(self) -> None: ... diff --git a/python/pyarrow-stubs/_stubs_typing.pyi b/python/pyarrow-stubs/_stubs_typing.pyi index 17ee2cffc316..bebb23dff607 100644 --- a/python/pyarrow-stubs/_stubs_typing.pyi +++ b/python/pyarrow-stubs/_stubs_typing.pyi @@ -24,6 +24,9 @@ from pyarrow.lib import Array, ChunkedArray from pyarrow import lib +Compression: TypeAlias = Literal[ + "gzip", "bz2", "brotli", "lz4", "lz4_frame", "lz4_raw", "zstd", "snappy" +] Order: TypeAlias = Literal["ascending", "descending"] MapsAsPydicts: TypeAlias = Literal["lossy", "strict"] NullEncoding: TypeAlias = Literal["mask", "encode"] @@ -36,6 +39,9 @@ Indices: TypeAlias = ( Sequence[int | None] | NDArray[np.integer[Any]] | Array | ChunkedArray ) +class SupportPyBuffer(Protocol): + def __buffer__(self, flags: int, /) -> memoryview: ... + class SupportsArrowStream(Protocol): def __arrow_c_stream__(self, requested_schema: Any = None, /) -> Any: ... diff --git a/python/pyarrow-stubs/csv.pyi b/python/pyarrow-stubs/csv.pyi new file mode 100644 index 000000000000..2061f96e5307 --- /dev/null +++ b/python/pyarrow-stubs/csv.pyi @@ -0,0 +1,30 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from pyarrow._csv import ( + ISO8601 as ISO8601, + ConvertOptions as ConvertOptions, + CSVStreamingReader as CSVStreamingReader, + CSVWriter as CSVWriter, + InvalidRow as InvalidRow, + ParseOptions as ParseOptions, + ReadOptions as ReadOptions, + WriteOptions as WriteOptions, + open_csv as open_csv, + read_csv as read_csv, + write_csv as write_csv, +) diff --git a/python/pyarrow-stubs/feather.pyi b/python/pyarrow-stubs/feather.pyi new file mode 100644 index 000000000000..287871edbe2a --- /dev/null +++ b/python/pyarrow-stubs/feather.pyi @@ -0,0 +1,62 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from collections.abc import Iterable +from typing import IO, Any, Literal + +import pandas as pd +from _typeshed import StrPath +from pyarrow import lib +from pyarrow.lib import Table + +from ._feather import FeatherError as FeatherError + +class FeatherDataset: + path_or_paths: str | list[str] + validate_schema: bool + + def __init__( + self, path_or_paths: str | list[str], validate_schema: bool = True + ) -> None: ... + def read_table(self, columns: list[str] | None = None) -> Table: ... + def validate_schemas(self, piece: Any, table: Table) -> None: ... + def read_pandas( + self, columns: list[str] | None = None, use_threads: bool = True + ) -> pd.DataFrame: ... + +def check_chunked_overflow(name: str, col: Any) -> None: ... +def write_feather( + df: pd.DataFrame | Table | lib.ChunkedArray, + dest: StrPath | IO[Any] | lib.NativeFile, + compression: Literal["zstd", "lz4", "uncompressed", "snappy"] | None = None, + compression_level: int | None = None, + chunksize: int | None = None, + version: Literal[1, 2] = 2, +) -> None: ... +def read_feather( + source: StrPath | IO[Any] | lib.NativeFile, + columns: list[str] | None = None, + use_threads: bool = True, + memory_map: bool = False, + **kwargs: Any, +) -> pd.DataFrame: ... +def read_table( + source: StrPath | IO[Any] | lib.NativeFile, + columns: Iterable[str | int] | None = None, + memory_map: bool = False, + use_threads: bool = True, +) -> Table: ... diff --git a/python/pyarrow-stubs/ipc.pyi b/python/pyarrow-stubs/ipc.pyi new file mode 100644 index 000000000000..b1daedb27dbd --- /dev/null +++ b/python/pyarrow-stubs/ipc.pyi @@ -0,0 +1,113 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from io import IOBase + +from _typeshed import StrPath +import pandas as pd +import pyarrow.lib as lib + +from pyarrow.lib import ( + Alignment as Alignment, + IpcReadOptions as IpcReadOptions, + IpcWriteOptions as IpcWriteOptions, + Message as Message, + MessageReader as MessageReader, + MetadataVersion as MetadataVersion, + ReadStats as ReadStats, + RecordBatchReader as RecordBatchReader, + WriteStats as WriteStats, + _ReadPandasMixin as _ReadPandasMixin, + get_record_batch_size as get_record_batch_size, + get_tensor_size as get_tensor_size, + read_message as read_message, + read_record_batch as read_record_batch, + read_schema as read_schema, + read_tensor as read_tensor, + write_tensor as write_tensor, +) + +class RecordBatchStreamReader(lib._RecordBatchStreamReader): + def __init__( + self, + source: bytes | lib.Buffer | lib.NativeFile | IOBase, + *, + options: IpcReadOptions | None = None, + memory_pool: lib.MemoryPool | None = None, + ) -> None: ... + +class RecordBatchStreamWriter(lib._RecordBatchStreamWriter): + def __init__( + self, + sink: str | lib.NativeFile | IOBase, + schema: lib.Schema, + *, + options: IpcWriteOptions | None = None, + ) -> None: ... + +class RecordBatchFileReader(lib._RecordBatchFileReader): + def __init__( + self, + source: bytes | lib.Buffer | lib.NativeFile | IOBase, + footer_offset: int | None = None, + *, + options: IpcReadOptions | None = None, + memory_pool: lib.MemoryPool | None = None, + ) -> None: ... + +class RecordBatchFileWriter(lib._RecordBatchFileWriter): + def __init__( + self, + sink: str | lib.NativeFile | IOBase, + schema: lib.Schema, + *, + options: IpcWriteOptions | None = None, + metadata: lib.KeyValueMetadata | dict[bytes, bytes] | None = None, + ) -> None: ... + +def new_stream( + sink: str | lib.NativeFile | IOBase, + schema: lib.Schema, + *, + options: IpcWriteOptions | None = None, +) -> RecordBatchStreamWriter: ... +def open_stream( + source: bytes | int | lib.Buffer | lib.NativeFile | IOBase, + *, + options: IpcReadOptions | None = None, + memory_pool: lib.MemoryPool | None = None, +) -> RecordBatchStreamReader: ... +def new_file( + sink: str | lib.NativeFile | IOBase, + schema: lib.Schema, + *, + options: IpcWriteOptions | None = None, + metadata: lib.KeyValueMetadata | dict[bytes, bytes] | None = None, +) -> RecordBatchFileWriter: ... +def open_file( + source: StrPath | bytes | lib.Buffer | lib.NativeFile | IOBase, + footer_offset: int | None = None, + *, + options: IpcReadOptions | None = None, + memory_pool: lib.MemoryPool | None = None, +) -> RecordBatchFileReader: ... +def serialize_pandas( + df: pd.DataFrame, *, nthreads: int | None = None, preserve_index: bool | None = None +) -> lib.Buffer: ... +def deserialize_pandas( + buf: lib.Buffer, *, use_threads: bool = True +) -> pd.DataFrame: ... diff --git a/python/pyarrow-stubs/json.pyi b/python/pyarrow-stubs/json.pyi new file mode 100644 index 000000000000..d67cf434b233 --- /dev/null +++ b/python/pyarrow-stubs/json.pyi @@ -0,0 +1,23 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from pyarrow._json import ( + ParseOptions as ParseOptions, + ReadOptions as ReadOptions, + open_json as open_json, + read_json as read_json, +) diff --git a/python/pyarrow-stubs/lib.pyi b/python/pyarrow-stubs/lib.pyi index 74624bfbcd47..6f656fff5944 100644 --- a/python/pyarrow-stubs/lib.pyi +++ b/python/pyarrow-stubs/lib.pyi @@ -27,6 +27,7 @@ from pyarrow.__lib.config import * # noqa: F401,F403 from pyarrow.__lib.device import * # noqa: F401,F403 from pyarrow.__lib.error import * # noqa: F401,F403 from pyarrow.__lib.io import * # noqa: F401,F403 +from pyarrow.__lib.ipc import * # noqa: F401,F403 from pyarrow.__lib.memory import * # noqa: F401,F403 from pyarrow.__lib.scalar import * # noqa: F401,F403 from pyarrow.__lib.table import * # noqa: F401,F403 diff --git a/python/pyarrow-stubs/orc.pyi b/python/pyarrow-stubs/orc.pyi new file mode 100644 index 000000000000..d47b6a184ee3 --- /dev/null +++ b/python/pyarrow-stubs/orc.pyi @@ -0,0 +1,115 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from collections.abc import Sequence +from typing import IO, Any, Literal, Self + +from _typeshed import StrPath + +from . import _orc +from .lib import KeyValueMetadata, NativeFile, RecordBatch, Schema, Table + +class ORCFile: + reader: _orc.ORCReader + def __init__(self, source: StrPath | NativeFile | IO[Any]) -> None: ... + @property + def metadata(self) -> KeyValueMetadata: ... + @property + def schema(self) -> Schema: ... + @property + def nrows(self) -> int: ... + @property + def nstripes(self) -> int: ... + @property + def file_version(self) -> str: ... + @property + def software_version(self) -> str: ... + @property + def compression( + self, + ) -> Literal["UNCOMPRESSED", "ZLIB", "SNAPPY", "LZ4", "ZSTD"]: ... + @property + def compression_size(self) -> int: ... + @property + def writer(self) -> str: ... + @property + def writer_version(self) -> str: ... + @property + def row_index_stride(self) -> int: ... + @property + def nstripe_statistics(self) -> int: ... + @property + def content_length(self) -> int: ... + @property + def stripe_statistics_length(self) -> int: ... + @property + def file_footer_length(self) -> int: ... + @property + def file_postscript_length(self) -> int: ... + @property + def file_length(self) -> int: ... + def read_stripe( + self, n: int, columns: Sequence[str | int] | None = None + ) -> RecordBatch: ... + def read(self, columns: Sequence[str | int] | None = None) -> Table: ... + +class ORCWriter: + writer: _orc.ORCWriter + is_open: bool + + def __init__( + self, + where: StrPath | NativeFile | IO[Any], + *, + file_version: str = "0.12", + batch_size: int = 1024, + stripe_size: int = ..., + compression: str = "uncompressed", + compression_block_size: int = 65536, + compression_strategy: str = "speed", + row_index_stride: int = 10000, + padding_tolerance: float = 0.0, + dictionary_key_size_threshold: float = 0.0, + bloom_filter_columns: Sequence[int] | None = None, + bloom_filter_fpp: float = 0.05, + ) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: object, **kwargs: Any) -> None: ... + def write(self, table: Table) -> None: ... + def close(self) -> None: ... + +def read_table( + source: StrPath | NativeFile | IO[Any], + columns: Sequence[str | int] | None = None, + filesystem: Any = None, +) -> Table: ... +def write_table( + table: Table, + where: StrPath | NativeFile | IO[Any], + *, + file_version: str = "0.12", + batch_size: int = 1024, + stripe_size: int = ..., + compression: str = "uncompressed", + compression_block_size: int = 65536, + compression_strategy: str = "speed", + row_index_stride: int = 10000, + padding_tolerance: float = 0.0, + dictionary_key_size_threshold: float = 0.0, + bloom_filter_columns: Sequence[int] | None = None, + bloom_filter_fpp: float = 0.05, +) -> None: ... From 42b2460215464cc788745c75d4492a28d6b51434 Mon Sep 17 00:00:00 2001 From: Rok Mihevc Date: Mon, 30 Nov 2026 18:27:59 +0100 Subject: [PATCH 30/33] GH-49196: [Python][Annotations] Add type stubs for filesystem modules --- python/pyarrow-stubs-tests/test_fs.py | 50 +++++++ python/pyarrow-stubs/_azurefs.pyi | 35 +++++ python/pyarrow-stubs/_fs.pyi | 183 ++++++++++++++++++++++++++ python/pyarrow-stubs/_gcsfs.pyi | 41 ++++++ python/pyarrow-stubs/_hdfs.pyi | 36 +++++ python/pyarrow-stubs/_s3fs.pyi | 90 +++++++++++++ python/pyarrow-stubs/fs.pyi | 70 ++++++++++ python/pyarrow-stubs/orc.pyi | 3 +- python/pyproject.toml | 1 + 9 files changed, 508 insertions(+), 1 deletion(-) create mode 100644 python/pyarrow-stubs-tests/test_fs.py create mode 100644 python/pyarrow-stubs/_azurefs.pyi create mode 100644 python/pyarrow-stubs/_fs.pyi create mode 100644 python/pyarrow-stubs/_gcsfs.pyi create mode 100644 python/pyarrow-stubs/_hdfs.pyi create mode 100644 python/pyarrow-stubs/_s3fs.pyi create mode 100644 python/pyarrow-stubs/fs.pyi diff --git a/python/pyarrow-stubs-tests/test_fs.py b/python/pyarrow-stubs-tests/test_fs.py new file mode 100644 index 000000000000..7d39439289b4 --- /dev/null +++ b/python/pyarrow-stubs-tests/test_fs.py @@ -0,0 +1,50 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from pathlib import Path +from typing import TYPE_CHECKING + +import pyarrow.fs as fs + +from _check import assert_type, check + + +def test_local_filesystem(tmp_path: Path) -> None: + local = fs.LocalFileSystem() + check(assert_type(local, fs.LocalFileSystem), fs.LocalFileSystem) + check(assert_type(local.type_name, str), str) + + info = local.get_file_info(str(tmp_path)) + check(assert_type(info, fs.FileInfo), fs.FileInfo) + check(assert_type(info.type, fs.FileType), fs.FileType) + check(assert_type(info.path, str), str) + + selector = fs.FileSelector(str(tmp_path), recursive=True) + infos = local.get_file_info(selector) + check(assert_type(infos, list[fs.FileInfo]), list) + + sub = fs.SubTreeFileSystem(str(tmp_path), local) + check(assert_type(sub, fs.SubTreeFileSystem), fs.SubTreeFileSystem) + + resolved_fs, resolved_path = fs.FileSystem.from_uri(tmp_path.as_uri()) + check(assert_type(resolved_fs, fs.FileSystem), fs.FileSystem) + check(assert_type(resolved_path, str), str) + + +def test_invalid_usage() -> None: + if TYPE_CHECKING: + fs.FileSelector(123) # type: ignore[arg-type] diff --git a/python/pyarrow-stubs/_azurefs.pyi b/python/pyarrow-stubs/_azurefs.pyi new file mode 100644 index 000000000000..ab0e3610f731 --- /dev/null +++ b/python/pyarrow-stubs/_azurefs.pyi @@ -0,0 +1,35 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from typing import Literal + +from ._fs import FileSystem + +class AzureFileSystem(FileSystem): + def __init__( + self, + account_name: str | None = None, + account_key: str | None = None, + blob_storage_authority: str | None = None, + dfs_storage_authority: str | None = None, + blob_storage_scheme: Literal["http", "https"] = "https", + dfs_storage_scheme: Literal["http", "https"] = "https", + sas_token: str | None = None, + tenant_id: str | None = None, + client_id: str | None = None, + client_secret: str | None = None, + ) -> None: ... diff --git a/python/pyarrow-stubs/_fs.pyi b/python/pyarrow-stubs/_fs.pyi new file mode 100644 index 000000000000..47588410d943 --- /dev/null +++ b/python/pyarrow-stubs/_fs.pyi @@ -0,0 +1,183 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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 datetime as dt +import enum +from abc import ABC, abstractmethod +from typing import TypeAlias, overload + +from _typeshed import StrPath +from fsspec import AbstractFileSystem + +from .lib import NativeFile, _Weakrefable + +class FileType(enum.IntFlag): + NotFound = 0 + Unknown = 1 + File = 2 + Directory = 3 + +class FileInfo(_Weakrefable): + def __init__( + self, + path: str, + type: FileType = ..., + *, + mtime: dt.datetime | float | None = None, + mtime_ns: int | None = None, + size: int | None = None, + ) -> None: ... + @property + def type(self) -> FileType: ... + @property + def is_file(self) -> bool: ... + @property + def path(self) -> str: ... + @property + def base_name(self) -> str: ... + @property + def size(self) -> int: ... + @property + def extension(self) -> str: ... + @property + def mtime(self) -> dt.datetime | None: ... + @property + def mtime_ns(self) -> int | None: ... + +class FileSelector(_Weakrefable): + base_dir: str + allow_not_found: bool + recursive: bool + def __init__( + self, base_dir: str, allow_not_found: bool = False, recursive: bool = False + ) -> None: ... + +class FileSystem(_Weakrefable): + @staticmethod + def from_uri(uri: str | StrPath) -> tuple[FileSystem, str]: ... + def equals(self, other: FileSystem | object) -> bool: ... + @property + def type_name(self) -> str: ... + @overload + def get_file_info(self, paths_or_selector: str) -> FileInfo: ... + @overload + def get_file_info( + self, paths_or_selector: list[str] | FileSelector + ) -> list[FileInfo]: ... + @overload + def get_file_info( + self, paths_or_selector: str | list[str] | FileSelector + ) -> FileInfo | list[FileInfo]: ... + def create_dir(self, path: str, *, recursive: bool = True) -> None: ... + def delete_dir(self, path: str) -> None: ... + def delete_dir_contents( + self, path: str, *, accept_root_dir: bool = False, missing_dir_ok: bool = False + ) -> None: ... + def move(self, src: str, dest: str) -> None: ... + def copy_file(self, src: str, dest: str) -> None: ... + def delete_file(self, path: str) -> None: ... + def open_input_file(self, path: str) -> NativeFile: ... + def open_input_stream( + self, + path: str, + compression: str | None = "detect", + buffer_size: int | None = None, + ) -> NativeFile: ... + def open_output_stream( + self, + path: str, + compression: str | None = "detect", + buffer_size: int | None = None, + metadata: dict[str, str] | None = None, + ) -> NativeFile: ... + def open_append_stream( + self, + path: str, + compression: str | None = "detect", + buffer_size: int | None = None, + metadata: dict[str, str] | None = None, + ) -> NativeFile: ... + def normalize_path(self, path: str) -> str: ... + +class LocalFileSystem(FileSystem): + def __init__(self, *, use_mmap: bool = False) -> None: ... + +class SubTreeFileSystem(FileSystem): + def __init__(self, base_path: str, base_fs: FileSystem) -> None: ... + @property + def base_path(self) -> str: ... + @property + def base_fs(self) -> FileSystem: ... + +class _MockFileSystem(FileSystem): + def __init__(self, current_time: dt.datetime | None = None) -> None: ... + +class PyFileSystem(FileSystem): + def __init__(self, handler: FileSystemHandler | None) -> None: ... + @property + def handler(self) -> FileSystemHandler: ... + +class FileSystemHandler(ABC): + @abstractmethod + def get_type_name(self) -> str: ... + @abstractmethod + def get_file_info(self, paths: str | list[str]) -> FileInfo | list[FileInfo]: ... + @abstractmethod + def get_file_info_selector(self, selector: FileSelector) -> list[FileInfo]: ... + @abstractmethod + def create_dir(self, path: str, recursive: bool) -> None: ... + @abstractmethod + def delete_dir(self, path: str) -> None: ... + @abstractmethod + def delete_dir_contents(self, path: str, missing_dir_ok: bool) -> None: ... + @abstractmethod + def delete_root_dir_contents(self) -> None: ... + @abstractmethod + def delete_file(self, path: str) -> None: ... + @abstractmethod + def move(self, src: str, dest: str) -> None: ... + @abstractmethod + def copy_file(self, src: str, dest: str) -> None: ... + @abstractmethod + def open_input_stream(self, path: str) -> NativeFile: ... + @abstractmethod + def open_input_file(self, path: str) -> NativeFile: ... + @abstractmethod + def open_output_stream(self, path: str, metadata: dict[str, str]) -> NativeFile: ... + @abstractmethod + def open_append_stream(self, path: str, metadata: dict[str, str]) -> NativeFile: ... + @abstractmethod + def normalize_path(self, path: str) -> str: ... + +_SupportedFileSystem: TypeAlias = AbstractFileSystem | FileSystem + +def _copy_files( + source_fs: FileSystem, + source_path: str, + destination_fs: _SupportedFileSystem | None, + destination_path: str, + chunk_size: int, + use_threads: bool, +) -> None: ... +def _copy_files_selector( + source_fs: FileSystem, + source_sel: FileSelector, + destination_fs: _SupportedFileSystem | None, + destination_base_dir: str, + chunk_size: int, + use_threads: bool, +) -> None: ... diff --git a/python/pyarrow-stubs/_gcsfs.pyi b/python/pyarrow-stubs/_gcsfs.pyi new file mode 100644 index 000000000000..ef1336b663ad --- /dev/null +++ b/python/pyarrow-stubs/_gcsfs.pyi @@ -0,0 +1,41 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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 datetime as dt + +from ._fs import FileSystem +from .lib import KeyValueMetadata + +class GcsFileSystem(FileSystem): + def __init__( + self, + *, + anonymous: bool = False, + access_token: str | None = None, + target_service_account: str | None = None, + credential_token_expiration: dt.datetime | None = None, + default_bucket_location: str = "US", + scheme: str = "https", + endpoint_override: str | None = None, + default_metadata: dict[str, str] | KeyValueMetadata | None = None, + retry_time_limit: dt.timedelta | None = None, + project_id: str | None = None, + ) -> None: ... + @property + def default_bucket_location(self) -> str: ... + @property + def project_id(self) -> str: ... diff --git a/python/pyarrow-stubs/_hdfs.pyi b/python/pyarrow-stubs/_hdfs.pyi new file mode 100644 index 000000000000..db2a71680b07 --- /dev/null +++ b/python/pyarrow-stubs/_hdfs.pyi @@ -0,0 +1,36 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from _typeshed import StrPath + +from ._fs import FileSystem + +class HadoopFileSystem(FileSystem): + def __init__( + self, + host: str | None = None, + port: int = 8020, + *, + user: str | None = None, + replication: int = 3, + buffer_size: int = 0, + default_block_size: int | None = None, + kerb_ticket: StrPath | None = None, + extra_conf: dict[str, str] | None = None, + ) -> None: ... + @staticmethod + def from_uri(uri: str | int) -> HadoopFileSystem: ... # type: ignore[override] diff --git a/python/pyarrow-stubs/_s3fs.pyi b/python/pyarrow-stubs/_s3fs.pyi new file mode 100644 index 000000000000..b7008b499102 --- /dev/null +++ b/python/pyarrow-stubs/_s3fs.pyi @@ -0,0 +1,90 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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 enum + +from typing import Any, Literal, TypedDict +from typing_extensions import Required, NotRequired + +from ._fs import FileSystem +from .lib import KeyValueMetadata + +class _ProxyOptions(TypedDict): + scheme: Required[Literal["http", "https"]] + host: Required[str] + port: Required[int] + username: NotRequired[str] + password: NotRequired[str] + +class S3LogLevel(enum.IntEnum): + Off = 0 + Fatal = 1 + Error = 2 + Warn = 3 + Info = 4 + Debug = 5 + Trace = 6 + +def initialize_s3( + log_level: S3LogLevel = ..., num_event_loop_threads: int = 1 +) -> None: ... +def ensure_s3_initialized() -> None: ... +def finalize_s3() -> None: ... +def ensure_s3_finalized() -> None: ... +def resolve_s3_region(bucket: str) -> str: ... + +class S3RetryStrategy: + max_attempts: int + def __init__(self, max_attempts: int = 3) -> None: ... + +class AwsStandardS3RetryStrategy(S3RetryStrategy): ... +class AwsDefaultS3RetryStrategy(S3RetryStrategy): ... + +class S3FileSystem(FileSystem): + def __init__( + self, + *, + access_key: str | None = None, + secret_key: str | None = None, + session_token: str | None = None, + anonymous: bool = False, + region: str | None = None, + request_timeout: float | None = None, + connect_timeout: float | None = None, + scheme: Literal["http", "https"] = "https", + endpoint_override: str | None = None, + background_writes: bool = True, + default_metadata: dict[Any, Any] | list[Any] | KeyValueMetadata | None = None, + role_arn: str | None = None, + session_name: str | None = None, + external_id: str | None = None, + load_frequency: int = 900, + proxy_options: _ProxyOptions + | dict[Any, Any] + | tuple[Any, ...] + | str + | None = None, + allow_bucket_creation: bool = False, + allow_bucket_deletion: bool = False, + allow_delayed_open: bool = False, + check_directory_existence_before_creation: bool = False, + tls_ca_file_path: str | None = None, + retry_strategy: S3RetryStrategy = ..., + force_virtual_addressing: bool = False, + ) -> None: ... + @property + def region(self) -> str: ... diff --git a/python/pyarrow-stubs/fs.pyi b/python/pyarrow-stubs/fs.pyi new file mode 100644 index 000000000000..b33e40f3da3a --- /dev/null +++ b/python/pyarrow-stubs/fs.pyi @@ -0,0 +1,70 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from pyarrow._azurefs import AzureFileSystem as AzureFileSystem +from pyarrow._fs import ( + FileInfo as FileInfo, + FileSelector as FileSelector, + FileSystem as FileSystem, + FileSystemHandler as FileSystemHandler, + FileType as FileType, + LocalFileSystem as LocalFileSystem, + PyFileSystem as PyFileSystem, + SubTreeFileSystem as SubTreeFileSystem, + _MockFileSystem as _MockFileSystem, + _SupportedFileSystem, +) +from pyarrow._gcsfs import GcsFileSystem as GcsFileSystem +from pyarrow._hdfs import HadoopFileSystem as HadoopFileSystem +from pyarrow._s3fs import ( + AwsDefaultS3RetryStrategy as AwsDefaultS3RetryStrategy, + AwsStandardS3RetryStrategy as AwsStandardS3RetryStrategy, + S3FileSystem as S3FileSystem, + S3LogLevel as S3LogLevel, + S3RetryStrategy as S3RetryStrategy, + ensure_s3_finalized as ensure_s3_finalized, + ensure_s3_initialized as ensure_s3_initialized, + finalize_s3 as finalize_s3, + initialize_s3 as initialize_s3, + resolve_s3_region as resolve_s3_region, +) + +FileStats = FileInfo + +def copy_files( + source: str, + destination: str, + source_filesystem: _SupportedFileSystem | None = None, + destination_filesystem: _SupportedFileSystem | None = None, + *, + chunk_size: int = ..., + use_threads: bool = True, +) -> None: ... +def _ensure_filesystem( + filesystem: FileSystem | str | object, *, use_mmap: bool = False +) -> FileSystem: ... +def _resolve_filesystem_and_path( + path: str | object, + filesystem: FileSystem | str | object | None = None, + *, + memory_map: bool = False, +) -> tuple[FileSystem, str]: ... + +# All abstract methods are implemented via fsspec delegation. +class FSSpecHandler(FileSystemHandler): # type: ignore[misc] + fs: _SupportedFileSystem + def __init__(self, fs: _SupportedFileSystem) -> None: ... diff --git a/python/pyarrow-stubs/orc.pyi b/python/pyarrow-stubs/orc.pyi index d47b6a184ee3..b18654c79dc6 100644 --- a/python/pyarrow-stubs/orc.pyi +++ b/python/pyarrow-stubs/orc.pyi @@ -21,6 +21,7 @@ from typing import IO, Any, Literal, Self from _typeshed import StrPath from . import _orc +from ._fs import _SupportedFileSystem from .lib import KeyValueMetadata, NativeFile, RecordBatch, Schema, Table class ORCFile: @@ -95,7 +96,7 @@ class ORCWriter: def read_table( source: StrPath | NativeFile | IO[Any], columns: Sequence[str | int] | None = None, - filesystem: Any = None, + filesystem: _SupportedFileSystem | str | None = None, ) -> Table: ... def write_table( table: Table, diff --git a/python/pyproject.toml b/python/pyproject.toml index ff68f4ce24dc..36623967b013 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -168,6 +168,7 @@ include = [ "pyarrow-stubs/__lib/array.pyi", "pyarrow-stubs/__lib/scalar.pyi", "pyarrow-stubs/_compute.pyi", + "pyarrow-stubs/_hdfs.pyi", ] [tool.ty.overrides.rules] # Some array and scalar classes override methods with a different signature at From 76acaa7a40da8eb189a4e585ffafd59277780644 Mon Sep 17 00:00:00 2001 From: Rok Mihevc Date: Mon, 30 Nov 2026 18:30:21 +0100 Subject: [PATCH 31/33] GH-49197: [Python][Annotations] Add type stubs for parquet and dataset modules --- .../test_parquet_dataset.py | 48 ++ python/pyarrow-stubs/_dataset.pyi | 595 ++++++++++++++++++ python/pyarrow-stubs/_dataset_orc.pyi | 23 + python/pyarrow-stubs/_dataset_parquet.pyi | 209 ++++++ .../_dataset_parquet_encryption.pyi | 55 ++ python/pyarrow-stubs/_parquet.pyi | 463 ++++++++++++++ python/pyarrow-stubs/_parquet_encryption.pyi | 149 +++++ python/pyarrow-stubs/_stubs_typing.pyi | 21 +- python/pyarrow-stubs/dataset.pyi | 200 ++++++ python/pyarrow-stubs/parquet/__init__.pyi | 18 + python/pyarrow-stubs/parquet/core.pyi | 361 +++++++++++ python/pyarrow-stubs/parquet/encryption.pyi | 27 + 12 files changed, 2167 insertions(+), 2 deletions(-) create mode 100644 python/pyarrow-stubs-tests/test_parquet_dataset.py create mode 100644 python/pyarrow-stubs/_dataset.pyi create mode 100644 python/pyarrow-stubs/_dataset_orc.pyi create mode 100644 python/pyarrow-stubs/_dataset_parquet.pyi create mode 100644 python/pyarrow-stubs/_dataset_parquet_encryption.pyi create mode 100644 python/pyarrow-stubs/_parquet.pyi create mode 100644 python/pyarrow-stubs/_parquet_encryption.pyi create mode 100644 python/pyarrow-stubs/dataset.pyi create mode 100644 python/pyarrow-stubs/parquet/__init__.pyi create mode 100644 python/pyarrow-stubs/parquet/core.pyi create mode 100644 python/pyarrow-stubs/parquet/encryption.pyi diff --git a/python/pyarrow-stubs-tests/test_parquet_dataset.py b/python/pyarrow-stubs-tests/test_parquet_dataset.py new file mode 100644 index 000000000000..261cb2de81f8 --- /dev/null +++ b/python/pyarrow-stubs-tests/test_parquet_dataset.py @@ -0,0 +1,48 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from pathlib import Path +from typing import TYPE_CHECKING + +import pyarrow as pa +import pyarrow.dataset as ds +import pyarrow.parquet as pq + +from _check import assert_type, check + + +def test_parquet_and_dataset(tmp_path: Path) -> None: + table = pa.table({"a": [1, 2, 3], "b": ["x", "y", "z"]}) + path = tmp_path / "data.parquet" + pq.write_table(table, path) + + read_back = pq.read_table(path) + check(assert_type(read_back, pa.Table), pa.Table) + + pf = pq.ParquetFile(path) + check(assert_type(pf.metadata, pq.FileMetaData), pq.FileMetaData) + check(assert_type(pf.num_row_groups, int), int) + check(assert_type(pf.read(), pa.Table), pa.Table) + + dset = ds.dataset(path, format="parquet") + check(assert_type(dset.schema, pa.Schema), pa.Schema) + check(assert_type(dset.to_table(), pa.Table), pa.Table) + + +def test_invalid_usage() -> None: + if TYPE_CHECKING: + ds.partitioning(flavor="invalid") # type: ignore[arg-type] diff --git a/python/pyarrow-stubs/_dataset.pyi b/python/pyarrow-stubs/_dataset.pyi new file mode 100644 index 000000000000..ca4fa879afd1 --- /dev/null +++ b/python/pyarrow-stubs/_dataset.pyi @@ -0,0 +1,595 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from collections.abc import Callable, Collection, Iterable, Iterator +from typing import ( + IO, + Any, + Generic, + Literal, + NamedTuple, + Self, + TypeVar, +) + +from _typeshed import StrPath + +from . import _json, _parquet, csv, lib +from ._acero import ExecNodeOptions +from ._fs import FileSelector, FileSystem, _SupportedFileSystem +from ._stubs_typing import Indices, JoinType, Order +from .compute import Expression +from .ipc import IpcWriteOptions, RecordBatchReader + +class Dataset(lib._Weakrefable): + @property + def partition_expression(self) -> Expression: ... + def replace_schema(self, schema: lib.Schema) -> Self: ... + def get_fragments(self, filter: Expression | None = None) -> Iterator[Fragment]: ... + def scanner( + self, + columns: list[str] | dict[str, Expression] | None = None, + filter: Expression | None = None, + batch_size: int = ..., + batch_readahead: int = 16, + fragment_readahead: int = 4, + fragment_scan_options: FragmentScanOptions | None = None, + use_threads: bool = True, + cache_metadata: bool = True, + memory_pool: lib.MemoryPool | None = None, + ) -> Scanner: ... + def to_batches( + self, + columns: list[str] | None = None, + filter: Expression | None = None, + batch_size: int = ..., + batch_readahead: int = 16, + fragment_readahead: int = 4, + fragment_scan_options: FragmentScanOptions | None = None, + use_threads: bool = True, + cache_metadata: bool = True, + memory_pool: lib.MemoryPool | None = None, + ) -> Iterator[lib.RecordBatch]: ... + def to_table( + self, + columns: list[str] | dict[str, Expression] | None = None, + filter: Expression | None = None, + batch_size: int = ..., + batch_readahead: int = 16, + fragment_readahead: int = 4, + fragment_scan_options: FragmentScanOptions | None = None, + use_threads: bool = True, + cache_metadata: bool = True, + memory_pool: lib.MemoryPool | None = None, + ) -> lib.Table: ... + def take( + self, + indices: Indices, + columns: list[str] | None = None, + filter: Expression | None = None, + batch_size: int = ..., + batch_readahead: int = 16, + fragment_readahead: int = 4, + fragment_scan_options: FragmentScanOptions | None = None, + use_threads: bool = True, + cache_metadata: bool = True, + memory_pool: lib.MemoryPool | None = None, + ) -> lib.Table: ... + def head( + self, + num_rows: int, + columns: list[str] | None = None, + filter: Expression | None = None, + batch_size: int = ..., + batch_readahead: int = 16, + fragment_readahead: int = 4, + fragment_scan_options: FragmentScanOptions | None = None, + use_threads: bool = True, + cache_metadata: bool = True, + memory_pool: lib.MemoryPool | None = None, + ) -> lib.Table: ... + def count_rows( + self, + filter: Expression | None = None, + batch_size: int = ..., + batch_readahead: int = 16, + fragment_readahead: int = 4, + fragment_scan_options: FragmentScanOptions | None = None, + use_threads: bool = True, + cache_metadata: bool = True, + memory_pool: lib.MemoryPool | None = None, + ) -> int: ... + @property + def schema(self) -> lib.Schema: ... + def filter(self, expression: Expression | None) -> Self: ... + def sort_by( + self, sorting: str | list[tuple[str, Order]], **kwargs: Any + ) -> InMemoryDataset: ... + def join( + self, + right_dataset: Dataset, + keys: str | list[str], + right_keys: str | list[str] | None = None, + join_type: JoinType = "left outer", + left_suffix: str | None = None, + right_suffix: str | None = None, + coalesce_keys: bool = True, + use_threads: bool = True, + ) -> InMemoryDataset: ... + def join_asof( + self, + right_dataset: Dataset, + on: str, + by: str | list[str], + tolerance: int, + right_on: str | list[str] | None = None, + right_by: str | list[str] | None = None, + ) -> InMemoryDataset: ... + @property + def format(self) -> FileFormat: ... + +class InMemoryDataset(Dataset): + def __init__( + self, + source: lib.Table + | lib.RecordBatch + | lib.RecordBatchReader + | Iterable[lib.RecordBatch] + | list[Any], + schema: lib.Schema | None = None, + ) -> None: ... + +class FilteredDataset(Dataset): + def __init__(self, child: Dataset, filter: Expression) -> None: ... + @property + def child(self) -> Dataset: ... + @property + def filter_expression(self) -> Expression: ... + +class UnionDataset(Dataset): + def __init__( + self, + schema: lib.Schema | None = None, + children: list[Dataset] | None = None, + ) -> None: ... + @property + def children(self) -> list[Dataset]: ... + +class FileSystemDataset(Dataset): + def __init__( + self, + fragments: list[Fragment], + schema: lib.Schema, + format: FileFormat, + filesystem: _SupportedFileSystem | None = None, + root_partition: Expression | None = None, + ) -> None: ... + @classmethod + def from_paths( + cls, + paths: list[str], + schema: lib.Schema | None = None, + format: FileFormat | None = None, + filesystem: _SupportedFileSystem | None = None, + partitions: list[Expression] | None = None, + root_partition: Expression | None = None, + ) -> FileSystemDataset: ... + @property + def filesystem(self) -> FileSystem: ... + @property + def partitioning(self) -> Partitioning | None: ... + @property + def files(self) -> list[str]: ... + +class FileWriteOptions(lib._Weakrefable): + @property + def format(self) -> FileFormat: ... + +class FileFormat(lib._Weakrefable): + def inspect( + self, file: StrPath | IO[Any], filesystem: _SupportedFileSystem | None = None + ) -> lib.Schema: ... + def make_fragment( + self, + file: StrPath | IO[Any] | lib.Buffer | lib.BufferReader, + filesystem: _SupportedFileSystem | None = None, + partition_expression: Expression | None = None, + *, + file_size: int | None = None, + ) -> Fragment: ... + def make_write_options(self) -> FileWriteOptions: ... + @property + def default_extname(self) -> str: ... + @property + def default_fragment_scan_options(self) -> FragmentScanOptions: ... + @default_fragment_scan_options.setter + def default_fragment_scan_options(self, options: FragmentScanOptions) -> None: ... + +class Fragment(lib._Weakrefable): + @property + def physical_schema(self) -> lib.Schema: ... + @property + def partition_expression(self) -> Expression: ... + def scanner( + self, + schema: lib.Schema | None = None, + columns: list[str] | None = None, + filter: Expression | None = None, + batch_size: int = ..., + batch_readahead: int = 16, + fragment_readahead: int = 4, + fragment_scan_options: FragmentScanOptions | None = None, + use_threads: bool = True, + cache_metadata: bool = True, + memory_pool: lib.MemoryPool | None = None, + ) -> Scanner: ... + def to_batches( + self, + schema: lib.Schema | None = None, + columns: list[str] | None = None, + filter: Expression | None = None, + batch_size: int = ..., + batch_readahead: int = 16, + fragment_readahead: int = 4, + fragment_scan_options: FragmentScanOptions | None = None, + use_threads: bool = True, + cache_metadata: bool = True, + memory_pool: lib.MemoryPool | None = None, + ) -> Iterator[lib.RecordBatch]: ... + def to_table( + self, + schema: lib.Schema | None = None, + columns: list[str] | None = None, + filter: Expression | None = None, + batch_size: int = ..., + batch_readahead: int = 16, + fragment_readahead: int = 4, + fragment_scan_options: FragmentScanOptions | None = None, + use_threads: bool = True, + cache_metadata: bool = True, + memory_pool: lib.MemoryPool | None = None, + ) -> lib.Table: ... + def take( + self, + indices: Indices, + columns: list[str] | None = None, + filter: Expression | None = None, + batch_size: int = ..., + batch_readahead: int = 16, + fragment_readahead: int = 4, + fragment_scan_options: FragmentScanOptions | None = None, + use_threads: bool = True, + cache_metadata: bool = True, + memory_pool: lib.MemoryPool | None = None, + ) -> lib.Table: ... + def head( + self, + num_rows: int, + columns: list[str] | None = None, + filter: Expression | None = None, + batch_size: int = ..., + batch_readahead: int = 16, + fragment_readahead: int = 4, + fragment_scan_options: FragmentScanOptions | None = None, + use_threads: bool = True, + cache_metadata: bool = True, + memory_pool: lib.MemoryPool | None = None, + ) -> lib.Table: ... + def count_rows( + self, + filter: Expression | None = None, + batch_size: int = ..., + batch_readahead: int = 16, + fragment_readahead: int = 4, + fragment_scan_options: FragmentScanOptions | None = None, + use_threads: bool = True, + cache_metadata: bool = True, + memory_pool: lib.MemoryPool | None = None, + ) -> int: ... + +class FilteredFragment(Fragment): + @property + def fragment(self) -> Fragment: ... + @property + def filter_expression(self) -> Expression: ... + +class FileFragment(Fragment): + def open(self) -> lib.NativeFile: ... + @property + def path(self) -> str: ... + @property + def filesystem(self) -> FileSystem: ... + @property + def buffer(self) -> lib.Buffer: ... + @property + def format(self) -> FileFormat: ... + +class FragmentScanOptions(lib._Weakrefable): + @property + def type_name(self) -> str: ... + +class IpcFileWriteOptions(FileWriteOptions): + @property + def write_options(self) -> IpcWriteOptions: ... + @write_options.setter + def write_options(self, write_options: IpcWriteOptions) -> None: ... + +class IpcFileFormat(FileFormat): + def equals(self, other: IpcFileFormat) -> bool: ... + def make_write_options(self, **kwargs: Any) -> IpcFileWriteOptions: ... + @property + def default_extname(self) -> str: ... + +class FeatherFileFormat(IpcFileFormat): ... + +class CsvFileFormat(FileFormat): + def __init__( + self, + parse_options: csv.ParseOptions | None = None, + default_fragment_scan_options: CsvFragmentScanOptions | None = None, + convert_options: csv.ConvertOptions | None = None, + read_options: csv.ReadOptions | None = None, + ) -> None: ... + def make_write_options(self, **kwargs: Any) -> CsvFileWriteOptions: ... + @property + def parse_options(self) -> csv.ParseOptions: ... + @parse_options.setter + def parse_options(self, parse_options: csv.ParseOptions) -> None: ... + def equals(self, other: CsvFileFormat) -> bool: ... + +class CsvFragmentScanOptions(FragmentScanOptions): + convert_options: csv.ConvertOptions + read_options: csv.ReadOptions + + def __init__( + self, + convert_options: csv.ConvertOptions | None = None, + read_options: csv.ReadOptions | None = None, + ) -> None: ... + def equals(self, other: CsvFragmentScanOptions) -> bool: ... + +class CsvFileWriteOptions(FileWriteOptions): + write_options: csv.WriteOptions + +class JsonFileFormat(FileFormat): + def __init__( + self, + default_fragment_scan_options: JsonFragmentScanOptions | None = None, + parse_options: _json.ParseOptions | None = None, + read_options: _json.ReadOptions | None = None, + ) -> None: ... + def equals(self, other: JsonFileFormat) -> bool: ... + +class JsonFragmentScanOptions(FragmentScanOptions): + parse_options: _json.ParseOptions + read_options: _json.ReadOptions + + def __init__( + self, + parse_options: _json.ParseOptions | None = None, + read_options: _json.ReadOptions | None = None, + ) -> None: ... + def equals(self, other: JsonFragmentScanOptions) -> bool: ... + +class Partitioning(lib._Weakrefable): + def parse(self, path: str) -> Expression: ... + def format(self, expr: Expression) -> tuple[str, str]: ... + @property + def schema(self) -> lib.Schema: ... + @property + def dictionaries(self) -> list[Any]: ... + +class PartitioningFactory(lib._Weakrefable): + @property + def type_name(self) -> str: ... + +class KeyValuePartitioning(Partitioning): + @property + def dictionaries(self) -> list[Any]: ... + +class DirectoryPartitioning(KeyValuePartitioning): + @staticmethod + def discover( + field_names: list[str] | None = None, + infer_dictionary: bool = False, + max_partition_dictionary_size: int = 0, + schema: lib.Schema | None = None, + segment_encoding: Literal["uri", "none"] = "uri", + ) -> PartitioningFactory: ... + def __init__( + self, + schema: lib.Schema, + dictionaries: dict[str, lib.Array] | None = None, + segment_encoding: Literal["uri", "none"] = "uri", + ) -> None: ... + +class HivePartitioning(KeyValuePartitioning): + def __init__( + self, + schema: lib.Schema, + dictionaries: dict[str, lib.Array] | None = None, + null_fallback: str = "__HIVE_DEFAULT_PARTITION__", + segment_encoding: Literal["uri", "none"] = "uri", + ) -> None: ... + @staticmethod + def discover( + infer_dictionary: bool = False, + max_partition_dictionary_size: int = 0, + null_fallback: str = "__HIVE_DEFAULT_PARTITION__", + schema: lib.Schema | None = None, + segment_encoding: Literal["uri", "none"] = "uri", + ) -> PartitioningFactory: ... + +class FilenamePartitioning(KeyValuePartitioning): + def __init__( + self, + schema: lib.Schema, + dictionaries: dict[str, lib.Array] | None = None, + segment_encoding: Literal["uri", "none"] = "uri", + ) -> None: ... + @staticmethod + def discover( + field_names: list[str] | None = None, + infer_dictionary: bool = False, + schema: lib.Schema | None = None, + segment_encoding: Literal["uri", "none"] = "uri", + ) -> PartitioningFactory: ... + +class DatasetFactory(lib._Weakrefable): + root_partition: Expression + def finish(self, schema: lib.Schema | None = None) -> Dataset: ... + def inspect( + self, + *, + promote_options: str = "default", + fragments: list[Fragment] | int | str | None = None, + ) -> lib.Schema: ... + def inspect_schemas(self) -> list[lib.Schema]: ... + +class FileSystemFactoryOptions(lib._Weakrefable): + partitioning: Partitioning + partitioning_factory: PartitioningFactory + partition_base_dir: str + exclude_invalid_files: bool + selector_ignore_prefixes: list[str] + + def __init__( + self, + partition_base_dir: str | None = None, + partitioning: Partitioning | PartitioningFactory | None = None, + exclude_invalid_files: bool | None = True, + selector_ignore_prefixes: list[str] | None = None, + ) -> None: ... + +class FileSystemDatasetFactory(DatasetFactory): + def __init__( + self, + filesystem: _SupportedFileSystem, + paths_or_selector: Collection[str] | FileSelector, + format: FileFormat, + options: FileSystemFactoryOptions | None = None, + ) -> None: ... + +class UnionDatasetFactory(DatasetFactory): + def __init__(self, factories: list[DatasetFactory]) -> None: ... + +_RecordBatchT = TypeVar("_RecordBatchT", bound=lib.RecordBatch) + +class RecordBatchIterator(lib._Weakrefable, Generic[_RecordBatchT]): + def __iter__(self) -> Self: ... + def __next__(self) -> _RecordBatchT: ... + +class TaggedRecordBatch(NamedTuple): + record_batch: lib.RecordBatch + fragment: Fragment + +class TaggedRecordBatchIterator(lib._Weakrefable): + def __iter__(self) -> Self: ... + def __next__(self) -> TaggedRecordBatch: ... + +class Scanner(lib._Weakrefable): + @staticmethod + def from_dataset( + dataset: Dataset, + *, + columns: list[str] | dict[str, Expression] | None = None, + filter: Expression | None = None, + batch_size: int = ..., + batch_readahead: int = 16, + fragment_readahead: int = 4, + fragment_scan_options: FragmentScanOptions | None = None, + use_threads: bool = True, + cache_metadata: bool = True, + memory_pool: lib.MemoryPool | None = None, + ) -> Scanner: ... + @staticmethod + def from_fragment( + fragment: Fragment, + *, + schema: lib.Schema | None = None, + columns: list[str] | dict[str, Expression] | None = None, + filter: Expression | None = None, + batch_size: int = ..., + batch_readahead: int = 16, + fragment_readahead: int = 4, + fragment_scan_options: FragmentScanOptions | None = None, + use_threads: bool = True, + cache_metadata: bool = True, + memory_pool: lib.MemoryPool | None = None, + ) -> Scanner: ... + @staticmethod + def from_batches( + source: Iterator[lib.RecordBatch] | RecordBatchReader | Any, + *, + schema: lib.Schema | None = None, + columns: list[str] | dict[str, Expression] | None = None, + filter: Expression | None = None, + batch_size: int = ..., + batch_readahead: int = 16, + fragment_readahead: int = 4, + fragment_scan_options: FragmentScanOptions | None = None, + use_threads: bool = True, + cache_metadata: bool = True, + memory_pool: lib.MemoryPool | None = None, + ) -> Scanner: ... + @property + def dataset_schema(self) -> lib.Schema: ... + @property + def projected_schema(self) -> lib.Schema: ... + def to_batches(self) -> Iterator[lib.RecordBatch]: ... + def scan_batches(self) -> TaggedRecordBatchIterator: ... + def to_table(self) -> lib.Table: ... + def take(self, indices: Indices) -> lib.Table: ... + def head(self, num_rows: int) -> lib.Table: ... + def count_rows(self) -> int: ... + def to_reader(self) -> RecordBatchReader: ... + +def get_partition_keys(partition_expression: Expression) -> dict[str, Any]: ... + +class WrittenFile(lib._Weakrefable): + path: str + metadata: _parquet.FileMetaData | None + size: int + def __init__( + self, path: str, metadata: _parquet.FileMetaData | None, size: int + ) -> None: ... + +def _filesystemdataset_write( + data: Scanner, + base_dir: StrPath, + basename_template: str, + filesystem: _SupportedFileSystem, + partitioning: Partitioning, + preserve_order: bool, + file_options: FileWriteOptions, + max_partitions: int, + file_visitor: Callable[[str], None] | None, + existing_data_behavior: Literal["error", "overwrite_or_ignore", "delete_matching"], + max_open_files: int, + max_rows_per_file: int, + min_rows_per_group: int, + max_rows_per_group: int, + create_dir: bool, +) -> None: ... + +class _ScanNodeOptions(ExecNodeOptions): + def _set_options(self, dataset: Dataset, scan_options: dict[str, Any]) -> None: ... + +class ScanNodeOptions(_ScanNodeOptions): + def __init__( + self, dataset: Dataset, *, require_sequenced_output: bool = False, **kwargs: Any + ) -> None: ... diff --git a/python/pyarrow-stubs/_dataset_orc.pyi b/python/pyarrow-stubs/_dataset_orc.pyi new file mode 100644 index 000000000000..ae20cb9b1e90 --- /dev/null +++ b/python/pyarrow-stubs/_dataset_orc.pyi @@ -0,0 +1,23 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from ._dataset import FileFormat + +class OrcFileFormat(FileFormat): + def equals(self, other: OrcFileFormat) -> bool: ... + @property + def default_extname(self) -> str: ... diff --git a/python/pyarrow-stubs/_dataset_parquet.pyi b/python/pyarrow-stubs/_dataset_parquet.pyi new file mode 100644 index 000000000000..d676e7d9a61e --- /dev/null +++ b/python/pyarrow-stubs/_dataset_parquet.pyi @@ -0,0 +1,209 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from collections.abc import Iterable +from typing import IO, Any, TypedDict + +from _typeshed import StrPath + +from ._compute import Expression +from ._dataset import ( + DatasetFactory, + FileFormat, + FileFragment, + FileWriteOptions, + Fragment, + FragmentScanOptions, + Partitioning, + PartitioningFactory, +) +from ._dataset_parquet_encryption import ParquetDecryptionConfig +from ._fs import FileSystem, _SupportedFileSystem +from ._parquet import FileDecryptionProperties, FileMetaData +from .lib import ( + Buffer, + BufferReader, + CacheOptions, + DataType, + LargeListType, + ListType, + NativeFile, + Schema, + _Weakrefable, +) + +parquet_encryption_enabled: bool + +class ParquetFileFormat(FileFormat): + def __init__( + self, + read_options: ParquetReadOptions | None = None, + default_fragment_scan_options: ParquetFragmentScanOptions | None = None, + *, + pre_buffer: bool = True, + coerce_int96_timestamp_unit: str | None = None, + thrift_string_size_limit: int | None = None, + thrift_container_size_limit: int | None = None, + page_checksum_verification: bool = False, + arrow_extensions_enabled: bool = True, + binary_type: DataType | None = None, + list_type: type[ListType | LargeListType] | None = None, + use_buffered_stream: bool = False, + buffer_size: int = 8192, + dictionary_columns: list[str] | set[str] | None = None, + decryption_properties: FileDecryptionProperties | None = None, + ) -> None: ... + @property + def read_options(self) -> ParquetReadOptions: ... + def make_write_options(self, **kwargs: Any) -> ParquetFileWriteOptions: ... + def equals(self, other: ParquetFileFormat) -> bool: ... + @property + def default_extname(self) -> str: ... + def make_fragment( + self, + file: StrPath | IO[Any] | Buffer | BufferReader, + filesystem: _SupportedFileSystem | None = None, + partition_expression: Expression | None = None, + row_groups: Iterable[int] | None = None, + *, + file_size: int | None = None, + ) -> Fragment: ... + +class _NameStats(TypedDict): + min: Any + max: Any + +class RowGroupInfo: + id: int + metadata: FileMetaData + schema: Schema + + def __init__(self, id: int, metadata: FileMetaData, schema: Schema) -> None: ... + @property + def num_rows(self) -> int: ... + @property + def total_byte_size(self) -> int: ... + @property + def statistics(self) -> dict[str, _NameStats]: ... + +class ParquetFileFragment(FileFragment): + def ensure_complete_metadata(self) -> None: ... + @property + def path(self) -> str: ... + @property + def filesystem(self) -> FileSystem: ... + def open(self) -> NativeFile: ... + @property + def row_groups(self) -> list[int]: ... + @property + def metadata(self) -> FileMetaData: ... + @property + def num_row_groups(self) -> int: ... + def split_by_row_group( + self, filter: Expression | None = None, schema: Schema | None = None + ) -> list[Fragment]: ... + def subset( + self, + filter: Expression | None = None, + schema: Schema | None = None, + row_group_ids: list[int] | None = None, + ) -> ParquetFileFormat: ... + +class ParquetReadOptions(_Weakrefable): + def __init__( + self, + dictionary_columns: list[str] | set[str] | None = None, + coerce_int96_timestamp_unit: str | None = None, + binary_type: DataType | None = None, + list_type: type[ListType | LargeListType] | None = None, + ) -> None: ... + @property + def dictionary_columns(self) -> set[str]: ... + @dictionary_columns.setter + def dictionary_columns(self, columns: list[str] | set[str]) -> None: ... + @property + def coerce_int96_timestamp_unit(self) -> str: ... + @coerce_int96_timestamp_unit.setter + def coerce_int96_timestamp_unit(self, unit: str) -> None: ... + @property + def binary_type(self) -> DataType: ... + @binary_type.setter + def binary_type(self, type: DataType | None) -> None: ... + @property + def list_type(self) -> type[ListType | LargeListType]: ... + @list_type.setter + def list_type(self, type: type[ListType | LargeListType] | None) -> None: ... + def equals(self, other: ParquetReadOptions) -> bool: ... + +class ParquetFileWriteOptions(FileWriteOptions): + def update(self, **kwargs: Any) -> None: ... + def _set_properties(self) -> None: ... + def _set_arrow_properties(self) -> None: ... + def _set_encryption_config(self) -> None: ... + # accept passthrough options used in tests + def __init__(self, **kwargs: Any) -> None: ... + +class ParquetFragmentScanOptions(FragmentScanOptions): + use_buffered_stream: bool + buffer_size: int + pre_buffer: bool + cache_options: CacheOptions | None + thrift_string_size_limit: int | None + thrift_container_size_limit: int | None + decryption_config: ParquetDecryptionConfig | None + decryption_properties: FileDecryptionProperties | None + parquet_decryption_config: ParquetDecryptionConfig | None + page_checksum_verification: bool + arrow_extensions_enabled: bool + + def __init__( + self, + *, + use_buffered_stream: bool = False, + buffer_size: int = 8192, + pre_buffer: bool = True, + cache_options: CacheOptions | None = None, + thrift_string_size_limit: int | None = None, + thrift_container_size_limit: int | None = None, + decryption_config: ParquetDecryptionConfig | None = None, + decryption_properties: FileDecryptionProperties | None = None, + page_checksum_verification: bool = False, + arrow_extensions_enabled: bool = True, + ) -> None: ... + def equals(self, other: ParquetFragmentScanOptions) -> bool: ... + +class ParquetFactoryOptions(_Weakrefable): + partition_base_dir: str | None + partitioning: Partitioning | PartitioningFactory | None + partitioning_factory: PartitioningFactory | None + validate_column_chunk_paths: bool + + def __init__( + self, + partition_base_dir: str | None = None, + partitioning: Partitioning | PartitioningFactory | None = None, + validate_column_chunk_paths: bool = False, + ) -> None: ... + +class ParquetDatasetFactory(DatasetFactory): + def __init__( + self, + metadata_path: str, + filesystem: _SupportedFileSystem, + format: FileFormat, + options: ParquetFactoryOptions | None = None, + ) -> None: ... diff --git a/python/pyarrow-stubs/_dataset_parquet_encryption.pyi b/python/pyarrow-stubs/_dataset_parquet_encryption.pyi new file mode 100644 index 000000000000..265475aacf8a --- /dev/null +++ b/python/pyarrow-stubs/_dataset_parquet_encryption.pyi @@ -0,0 +1,55 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from ._dataset_parquet import ParquetFileWriteOptions, ParquetFragmentScanOptions +from ._parquet import FileDecryptionProperties +from ._parquet_encryption import ( + CryptoFactory, + EncryptionConfiguration, + DecryptionConfiguration, + KmsConnectionConfig, +) +from .lib import _Weakrefable + +class ParquetEncryptionConfig(_Weakrefable): + def __init__( + self, + crypto_factory: CryptoFactory, + kms_connection_config: KmsConnectionConfig, + encryption_config: EncryptionConfiguration, + ) -> None: ... + +class ParquetDecryptionConfig(_Weakrefable): + def __init__( + self, + crypto_factory: CryptoFactory, + kms_connection_config: KmsConnectionConfig, + decryption_config: DecryptionConfiguration, + ) -> None: ... + +def set_encryption_config( + opts: ParquetFileWriteOptions, + config: ParquetEncryptionConfig, +) -> None: ... +def set_decryption_properties( + opts: ParquetFragmentScanOptions, + config: FileDecryptionProperties, +) -> None: ... +def set_decryption_config( + opts: ParquetFragmentScanOptions, + config: ParquetDecryptionConfig, +) -> None: ... diff --git a/python/pyarrow-stubs/_parquet.pyi b/python/pyarrow-stubs/_parquet.pyi new file mode 100644 index 000000000000..502d72663754 --- /dev/null +++ b/python/pyarrow-stubs/_parquet.pyi @@ -0,0 +1,463 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from collections.abc import Iterable, Iterator, Sequence +from typing import IO, Any, Literal, TypeAlias, TypedDict + +from _typeshed import StrPath + +from ._stubs_typing import Order +from .lib import ( + Buffer, + ChunkedArray, + KeyValueMetadata, + MemoryPool, + NativeFile, + RecordBatch, + Schema, + Table, + _Weakrefable, + DataType, +) + +_PhysicalType: TypeAlias = Literal[ + "BOOLEAN", + "INT32", + "INT64", + "INT96", + "FLOAT", + "DOUBLE", + "BYTE_ARRAY", + "FIXED_LEN_BYTE_ARRAY", + "UNKNOWN", +] +_LogicTypeName: TypeAlias = Literal[ + "UNDEFINED", + "STRING", + "MAP", + "LIST", + "ENUM", + "DECIMAL", + "DATE", + "TIME", + "TIMESTAMP", + "INT", + "FLOAT16", + "JSON", + "BSON", + "UUID", + "NONE", + "UNKNOWN", +] +_ConvertedType: TypeAlias = Literal[ + "NONE", + "UTF8", + "MAP", + "MAP_KEY_VALUE", + "LIST", + "ENUM", + "DECIMAL", + "DATE", + "TIME_MILLIS", + "TIME_MICROS", + "TIMESTAMP_MILLIS", + "TIMESTAMP_MICROS", + "UINT_8", + "UINT_16", + "UINT_32", + "UINT_64", + "INT_8", + "INT_16", + "INT_32", + "INT_64", + "JSON", + "BSON", + "INTERVAL", + "UNKNOWN", +] +_Encoding: TypeAlias = Literal[ + "PLAIN", + "PLAIN_DICTIONARY", + "RLE", + "BIT_PACKED", + "DELTA_BINARY_PACKED", + "DELTA_LENGTH_BYTE_ARRAY", + "DELTA_BYTE_ARRAY", + "RLE_DICTIONARY", + "BYTE_STREAM_SPLIT", + "UNKNOWN", +] +_Compression: TypeAlias = Literal[ + "UNCOMPRESSED", + "SNAPPY", + "GZIP", + "LZO", + "BROTLI", + "LZ4", + "ZSTD", + "UNKNOWN", +] + +class _Statistics(TypedDict): + has_min_max: bool + min: Any | None + max: Any | None + null_count: int | None + distinct_count: int | None + num_values: int + physical_type: _PhysicalType + +class Statistics(_Weakrefable): + def to_dict(self) -> _Statistics: ... + def equals(self, other: Statistics) -> bool: ... + @property + def has_min_max(self) -> bool: ... + @property + def has_null_count(self) -> bool: ... + @property + def has_distinct_count(self) -> bool: ... + @property + def min_raw(self) -> Any | None: ... + @property + def max_raw(self) -> Any | None: ... + @property + def min(self) -> Any | None: ... + @property + def max(self) -> Any | None: ... + @property + def null_count(self) -> int | None: ... + @property + def distinct_count(self) -> int | None: ... + @property + def num_values(self) -> int: ... + @property + def physical_type(self) -> _PhysicalType: ... + @property + def logical_type(self) -> ParquetLogicalType: ... + @property + def converted_type(self) -> _ConvertedType | None: ... + +class GeoStatistics(_Weakrefable): + def to_dict(self) -> dict[str, Any]: ... + @property + def geospatial_types(self) -> list[int] | None: ... + @property + def xmin(self) -> float | None: ... + @property + def xmax(self) -> float | None: ... + @property + def ymin(self) -> float | None: ... + @property + def ymax(self) -> float | None: ... + @property + def zmin(self) -> float | None: ... + @property + def zmax(self) -> float | None: ... + @property + def mmin(self) -> float | None: ... + @property + def mmax(self) -> float | None: ... + +class ParquetLogicalType(_Weakrefable): + def to_json(self) -> str: ... + @property + def type(self) -> _LogicTypeName: ... + +class _ColumnChunkMetaData(TypedDict): + file_offset: int + file_path: str | None + physical_type: _PhysicalType + num_values: int + path_in_schema: str + is_stats_set: bool + statistics: Statistics | None + compression: _Compression + encodings: tuple[_Encoding, ...] + has_dictionary_page: bool + dictionary_page_offset: int | None + data_page_offset: int + total_compressed_size: int + total_uncompressed_size: int + +class ColumnChunkMetaData(_Weakrefable): + def to_dict(self) -> _ColumnChunkMetaData: ... + def equals(self, other: ColumnChunkMetaData) -> bool: ... + @property + def file_offset(self) -> int: ... + @property + def file_path(self) -> str | None: ... + @property + def physical_type(self) -> _PhysicalType: ... + @property + def num_values(self) -> int: ... + @property + def path_in_schema(self) -> str: ... + @property + def is_stats_set(self) -> bool: ... + @property + def statistics(self) -> Statistics | None: ... + @property + def is_geo_stats_set(self) -> bool: ... + @property + def geo_statistics(self) -> GeoStatistics | None: ... + @property + def compression(self) -> _Compression: ... + @property + def encodings(self) -> tuple[_Encoding, ...]: ... + @property + def has_dictionary_page(self) -> bool: ... + @property + def dictionary_page_offset(self) -> int | None: ... + @property + def data_page_offset(self) -> int: ... + @property + def has_index_page(self) -> bool: ... + @property + def index_page_offset(self) -> int: ... + @property + def total_compressed_size(self) -> int: ... + @property + def total_uncompressed_size(self) -> int: ... + @property + def has_offset_index(self) -> bool: ... + @property + def has_column_index(self) -> bool: ... + @property + def metadata(self) -> dict[bytes, bytes] | None: ... + +class _SortingColumn(TypedDict): + column_index: int + descending: bool + nulls_first: bool + +class SortingColumn: + def __init__( + self, column_index: int, descending: bool = False, nulls_first: bool = False + ) -> None: ... + @classmethod + def from_ordering( + cls, + schema: Schema, + sort_keys: Sequence[str] + | Sequence[tuple[str, Order]] + | Sequence[str | tuple[str, Order]], + null_placement: Literal["at_start", "at_end"] = "at_end", + ) -> tuple[SortingColumn, ...]: ... + @staticmethod + def to_ordering( + schema: Schema, sorting_columns: tuple[SortingColumn, ...] | list[SortingColumn] + ) -> tuple[Sequence[tuple[str, Order]], Literal["at_start", "at_end"]]: ... + def __hash__(self) -> int: ... + @property + def column_index(self) -> int: ... + @property + def descending(self) -> bool: ... + @property + def nulls_first(self) -> bool: ... + def to_dict(self) -> _SortingColumn: ... + +class _RowGroupMetaData(TypedDict): + num_columns: int + num_rows: int + total_byte_size: int + columns: list[ColumnChunkMetaData] + sorting_columns: list[SortingColumn] + +class RowGroupMetaData(_Weakrefable): + def __init__(self, parent: FileMetaData, index: int) -> None: ... + def equals(self, other: RowGroupMetaData) -> bool: ... + def column(self, i: int) -> ColumnChunkMetaData: ... + def to_dict(self) -> _RowGroupMetaData: ... + @property + def num_columns(self) -> int: ... + @property + def num_rows(self) -> int: ... + @property + def total_byte_size(self) -> int: ... + @property + def sorting_columns(self) -> list[SortingColumn]: ... + +class _FileMetaData(TypedDict): + created_by: str + num_columns: int + num_rows: int + num_row_groups: int + format_version: str + serialized_size: int + row_groups: list[Any] # List of row group metadata dictionaries + +class FileMetaData(_Weakrefable): + def __hash__(self) -> int: ... + def to_dict(self) -> _FileMetaData: ... + def equals(self, other: FileMetaData) -> bool: ... + @property + def schema(self) -> ParquetSchema: ... + @property + def serialized_size(self) -> int: ... + @property + def num_columns(self) -> int: ... + @property + def num_rows(self) -> int: ... + @property + def num_row_groups(self) -> int: ... + @property + def format_version(self) -> str: ... + @property + def created_by(self) -> str: ... + @property + def metadata(self) -> dict[bytes, bytes] | None: ... + def row_group(self, i: int) -> RowGroupMetaData: ... + def set_file_path(self, path: str) -> None: ... + def append_row_groups(self, other: FileMetaData) -> None: ... + def write_metadata_file( + self, where: StrPath | Buffer | NativeFile | IO[Any] + ) -> None: ... + +class ParquetSchema(_Weakrefable): + def __init__(self, container: FileMetaData) -> None: ... + def __getitem__(self, i: int, /) -> ColumnSchema: ... + def __hash__(self) -> int: ... + def __len__(self) -> int: ... + @property + def names(self) -> list[str]: ... + def to_arrow_schema(self) -> Schema: ... + def equals(self, other: ParquetSchema) -> bool: ... + def column(self, i: int) -> ColumnSchema: ... + +class ColumnSchema(_Weakrefable): + def __init__(self, schema: ParquetSchema, index: int) -> None: ... + def equals(self, other: ColumnSchema) -> bool: ... + @property + def name(self) -> str: ... + @property + def path(self) -> str: ... + @property + def max_definition_level(self) -> int: ... + @property + def max_repetition_level(self) -> int: ... + @property + def physical_type(self) -> _PhysicalType: ... + @property + def logical_type(self) -> ParquetLogicalType: ... + @property + def converted_type(self) -> _ConvertedType | None: ... + @property + def length(self) -> int | None: ... + @property + def precision(self) -> int | None: ... + @property + def scale(self) -> int | None: ... + +class ParquetReader(_Weakrefable): + def __init__(self, memory_pool: MemoryPool | None = None) -> None: ... + def open( + self, + source: StrPath | Buffer | NativeFile | IO[Any], + *, + use_memory_map: bool = False, + read_dictionary: Iterable[int] | Iterable[str] | None = None, + metadata: FileMetaData | None = None, + binary_type: DataType | None = None, + list_type: DataType | None = None, + buffer_size: int = 0, + pre_buffer: bool = False, + coerce_int96_timestamp_unit: str | None = None, + decryption_properties: FileDecryptionProperties | None = None, + thrift_string_size_limit: int | None = None, + thrift_container_size_limit: int | None = None, + page_checksum_verification: bool = False, + arrow_extensions_enabled: bool = False, + ) -> None: ... + @property + def column_paths(self) -> list[str]: ... + @property + def metadata(self) -> FileMetaData: ... + @property + def schema_arrow(self) -> Schema: ... + @property + def num_row_groups(self) -> int: ... + def set_use_threads(self, use_threads: bool) -> None: ... + def set_batch_size(self, batch_size: int) -> None: ... + def iter_batches( + self, + batch_size: int, + row_groups: list[int] | range, + column_indices: list[str] | list[int] | None = None, + use_threads: bool = True, + ) -> Iterator[RecordBatch]: ... + def read_row_group( + self, i: int, column_indices: list[int] | None = None, use_threads: bool = True + ) -> Table: ... + def read_row_groups( + self, + row_groups: Sequence[int] | range, + column_indices: list[str] | list[int] | None = None, + use_threads: bool = True, + ) -> Table: ... + def read_all( + self, column_indices: list[int] | None = None, use_threads: bool = True + ) -> Table: ... + def scan_contents( + self, + column_indices: Sequence[str] | Sequence[int] | None = None, + batch_size: int = 65536, + ) -> int: ... + def column_name_idx(self, column_name: str) -> int: ... + def read_column(self, column_index: int) -> ChunkedArray: ... + def close(self) -> None: ... + @property + def closed(self) -> bool: ... + +class ParquetWriter(_Weakrefable): + def __init__( + self, + where: StrPath | NativeFile | IO[Any], + schema: Schema, + use_dictionary: bool | list[str] | None = None, + compression: _Compression | dict[str, _Compression] | str | None = None, + version: str | None = None, + write_statistics: bool | list[str] | None = None, + memory_pool: MemoryPool | None = None, + use_deprecated_int96_timestamps: bool = False, + coerce_timestamps: Literal["ms", "us"] | None = None, + data_page_size: int | None = None, + allow_truncated_timestamps: bool = False, + compression_level: int | dict[str, int] | None = None, + use_byte_stream_split: bool | list[str] = False, + column_encoding: _Encoding | dict[str, _Encoding] | None = None, + writer_engine_version: str | None = None, + data_page_version: str | None = None, + use_compliant_nested_type: bool = True, + encryption_properties: FileDecryptionProperties | None = None, + write_batch_size: int | None = None, + dictionary_pagesize_limit: int | None = None, + store_schema: bool = True, + write_page_index: bool = False, + write_page_checksum: bool = False, + sorting_columns: tuple[SortingColumn, ...] | None = None, + store_decimal_as_integer: bool = False, + write_time_adjusted_to_utc: bool = False, + max_rows_per_page: int | None = None, + ) -> None: ... + def close(self) -> None: ... + def write_table(self, table: Table, row_group_size: int | None = None) -> None: ... + def add_key_value_metadata(self, key_value_metadata: KeyValueMetadata) -> None: ... + @property + def metadata(self) -> FileMetaData: ... + +class FileEncryptionProperties: ... +class FileDecryptionProperties: ... diff --git a/python/pyarrow-stubs/_parquet_encryption.pyi b/python/pyarrow-stubs/_parquet_encryption.pyi new file mode 100644 index 000000000000..180981629ddf --- /dev/null +++ b/python/pyarrow-stubs/_parquet_encryption.pyi @@ -0,0 +1,149 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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 datetime as dt +import pathlib + +from collections.abc import Callable + +from pyarrow._fs import FileSystem +from ._parquet import FileDecryptionProperties, FileEncryptionProperties +from .lib import _Weakrefable + +class EncryptionConfiguration(_Weakrefable): + footer_key: str + column_keys: dict[str, list[str]] + encryption_algorithm: str + plaintext_footer: bool + double_wrapping: bool + cache_lifetime: dt.timedelta + internal_key_material: bool + data_key_length_bits: int + uniform_encryption: bool + + def __init__( + self, + footer_key: str, + *, + column_keys: dict[str, str | list[str]] | None = None, + encryption_algorithm: str | None = None, + plaintext_footer: bool | None = None, + double_wrapping: bool | None = None, + cache_lifetime: dt.timedelta | None = None, + internal_key_material: bool | None = None, + data_key_length_bits: int | None = None, + uniform_encryption: bool | None = None, + ) -> None: ... + +class DecryptionConfiguration(_Weakrefable): + cache_lifetime: dt.timedelta + def __init__(self, *, cache_lifetime: dt.timedelta | None = None) -> None: ... + +class KmsConnectionConfig(_Weakrefable): + kms_instance_id: str + kms_instance_url: str + key_access_token: str + custom_kms_conf: dict[str, str] + + def __init__( + self, + *, + kms_instance_id: str | None = None, + kms_instance_url: str | None = None, + key_access_token: str | None = None, + custom_kms_conf: dict[str, str] | None = None, + ) -> None: ... + def refresh_key_access_token(self, value: str) -> None: ... + +class KmsClient(_Weakrefable): + def wrap_key(self, key_bytes: bytes, master_key_identifier: str) -> str: ... + def unwrap_key(self, wrapped_key: str, master_key_identifier: str) -> bytes: ... + +class CryptoFactory(_Weakrefable): + def __init__( + self, kms_client_factory: Callable[[KmsConnectionConfig], KmsClient] + ) -> None: ... + def file_encryption_properties( + self, + kms_connection_config: KmsConnectionConfig, + encryption_config: EncryptionConfiguration, + parquet_file_path: str | pathlib.Path | None = None, + filesystem: FileSystem | None = None, + ) -> FileEncryptionProperties: ... + def file_decryption_properties( + self, + kms_connection_config: KmsConnectionConfig, + decryption_config: DecryptionConfiguration | None = None, + parquet_file_path: str | pathlib.Path | None = None, + filesystem: FileSystem | None = None, + ) -> FileDecryptionProperties: ... + def remove_cache_entries_for_token(self, access_token: str) -> None: ... + def remove_cache_entries_for_all_tokens(self) -> None: ... + def rotate_master_keys( + self, + kms_connection_config: KmsConnectionConfig, + parquet_file_path: str | pathlib.Path, + filesystem: FileSystem | None = None, + double_wrapping: bool = True, + cache_lifetime_seconds: float = 600, + ) -> None: ... + +class KeyMaterial(_Weakrefable): + @property + def is_footer_key(self) -> bool: ... + @property + def is_double_wrapped(self) -> bool: ... + @property + def master_key_id(self) -> str: ... + @property + def wrapped_dek(self) -> str: ... + @property + def kek_id(self) -> str: ... + @property + def wrapped_kek(self) -> str: ... + @property + def kms_instance_id(self) -> str: ... + @property + def kms_instance_url(self) -> str: ... + @staticmethod + def parse(key_material_string: str) -> KeyMaterial: ... + +class FileSystemKeyMaterialStore(_Weakrefable): + def get_key_material(self, key_id: str) -> KeyMaterial: ... + def get_key_id_set(self) -> list[str]: ... + @classmethod + def for_file( + cls, + parquet_file_path: str | pathlib.Path, + filesystem: FileSystem | None = None, + ) -> FileSystemKeyMaterialStore: ... + +def create_encryption_properties( + footer_key: bytes, + *, + aad_prefix: bytes | None = None, + store_aad_prefix: bool = True, + encryption_algorithm: str = "AES_GCM_V1", + plaintext_footer: bool = False, +) -> FileEncryptionProperties: ... +def create_decryption_properties( + footer_key: bytes, + *, + aad_prefix: bytes | None = None, + check_footer_integrity: bool = True, + allow_plaintext_files: bool = False, +) -> FileDecryptionProperties: ... diff --git a/python/pyarrow-stubs/_stubs_typing.pyi b/python/pyarrow-stubs/_stubs_typing.pyi index bebb23dff607..f4db088e8664 100644 --- a/python/pyarrow-stubs/_stubs_typing.pyi +++ b/python/pyarrow-stubs/_stubs_typing.pyi @@ -15,8 +15,8 @@ # specific language governing permissions and limitations # under the License. -from collections.abc import Sequence -from typing import Any, Literal, Protocol, TypeAlias +from collections.abc import Collection, Sequence +from typing import Any, Literal, Protocol, TypeAlias, TypeVar import numpy as np from numpy.typing import NDArray @@ -24,9 +24,26 @@ from pyarrow.lib import Array, ChunkedArray from pyarrow import lib +_T = TypeVar("_T") +SingleOrList: TypeAlias = list[_T] | _T + Compression: TypeAlias = Literal[ "gzip", "bz2", "brotli", "lz4", "lz4_frame", "lz4_raw", "zstd", "snappy" ] +JoinType: TypeAlias = Literal[ + "left semi", + "right semi", + "left anti", + "right anti", + "inner", + "left outer", + "right outer", + "full outer", +] +FilterTuple: TypeAlias = ( + tuple[str, Literal["=", "==", "!=", "<", ">", "<=", ">="], Any] + | tuple[str, Literal["in", "not in"], Collection[Any]] +) Order: TypeAlias = Literal["ascending", "descending"] MapsAsPydicts: TypeAlias = Literal["lossy", "strict"] NullEncoding: TypeAlias = Literal["mask", "encode"] diff --git a/python/pyarrow-stubs/dataset.pyi b/python/pyarrow-stubs/dataset.pyi new file mode 100644 index 000000000000..740a010c6f4b --- /dev/null +++ b/python/pyarrow-stubs/dataset.pyi @@ -0,0 +1,200 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from collections.abc import Callable, Iterable, Sequence +from typing import Literal, TypeAlias, Any + +from _typeshed import StrPath +from pyarrow._dataset import ( + CsvFileFormat, + CsvFragmentScanOptions, + Dataset, + DatasetFactory, + DirectoryPartitioning, + FeatherFileFormat, + FileFormat, + FileFragment, + FilenamePartitioning, + FileSystemDataset, + FileSystemDatasetFactory, + FileSystemFactoryOptions, + FileWriteOptions, + FilteredDataset, + FilteredFragment, + Fragment, + FragmentScanOptions, + HivePartitioning, + InMemoryDataset, + IpcFileFormat, + IpcFileWriteOptions, + JsonFileFormat, + JsonFragmentScanOptions, + Partitioning, + PartitioningFactory, + Scanner, + TaggedRecordBatch, + UnionDataset, + UnionDatasetFactory, + WrittenFile, + get_partition_keys, +) +from pyarrow._dataset_orc import OrcFileFormat +from pyarrow._dataset_parquet import ( + ParquetDatasetFactory, + ParquetFactoryOptions, + ParquetFileFormat, + ParquetFileFragment, + ParquetFileWriteOptions, + ParquetFragmentScanOptions, + ParquetReadOptions, + RowGroupInfo, +) +from pyarrow._dataset_parquet_encryption import ( + ParquetDecryptionConfig, + ParquetEncryptionConfig, +) +from pyarrow.compute import Expression, field, scalar +from pyarrow.lib import Array, RecordBatch, RecordBatchReader, Schema, Table + +from ._fs import _SupportedFileSystem + +_orc_available: bool +_parquet_available: bool + +__all__ = [ + "CsvFileFormat", + "CsvFragmentScanOptions", + "Dataset", + "DatasetFactory", + "DirectoryPartitioning", + "FeatherFileFormat", + "FileFormat", + "FileFragment", + "FilenamePartitioning", + "FileSystemDataset", + "FileSystemDatasetFactory", + "FileSystemFactoryOptions", + "FileWriteOptions", + "FilteredDataset", + "FilteredFragment", + "Fragment", + "FragmentScanOptions", + "HivePartitioning", + "InMemoryDataset", + "IpcFileFormat", + "IpcFileWriteOptions", + "JsonFileFormat", + "JsonFragmentScanOptions", + "Partitioning", + "PartitioningFactory", + "Scanner", + "TaggedRecordBatch", + "UnionDataset", + "UnionDatasetFactory", + "WrittenFile", + "get_partition_keys", + # Orc + "OrcFileFormat", + # Parquet + "ParquetDatasetFactory", + "ParquetFactoryOptions", + "ParquetFileFormat", + "ParquetFileFragment", + "ParquetFileWriteOptions", + "ParquetFragmentScanOptions", + "ParquetReadOptions", + "RowGroupInfo", + # Parquet Encryption + "ParquetDecryptionConfig", + "ParquetEncryptionConfig", + # Compute + "Expression", + "field", + "scalar", + # Dataset + "partitioning", + "parquet_dataset", + "write_dataset", +] + +_DatasetFormat: TypeAlias = Literal[ + "parquet", "ipc", "arrow", "feather", "csv", "json", "orc" +] + +def partitioning( + schema: Schema | None = None, + field_names: list[str] | None = None, + flavor: Literal["hive"] | None = None, + dictionaries: dict[str, Array] | Literal["infer"] | None = None, +) -> Partitioning | PartitioningFactory: ... +def parquet_dataset( + metadata_path: StrPath, + schema: Schema | None = None, + filesystem: _SupportedFileSystem | None = None, + format: ParquetFileFormat | None = None, + partitioning: Partitioning | PartitioningFactory | str | None = None, + partition_base_dir: str | None = None, +) -> FileSystemDataset: ... +def dataset( + source: StrPath + | Sequence[Dataset] + | Sequence[StrPath] + | Iterable[RecordBatch] + | Iterable[Table] + | RecordBatchReader + | RecordBatch + | Table, + schema: Schema | None = None, + format: FileFormat | _DatasetFormat | None = None, + filesystem: _SupportedFileSystem | str | None = None, + partitioning: Partitioning | PartitioningFactory | str | list[str] | None = None, + partition_base_dir: str | None = None, + exclude_invalid_files: bool | None = None, + ignore_prefixes: list[str] | None = None, +) -> FileSystemDataset | UnionDataset | InMemoryDataset | Dataset: ... +def write_dataset( + data: Any + | Dataset + | Table + | RecordBatch + | RecordBatchReader + | list[Table] + | Iterable[RecordBatch] + | Scanner, + base_dir: StrPath, + *, + basename_template: str | None = None, + format: FileFormat | _DatasetFormat | None = None, + partitioning: Partitioning | PartitioningFactory | list[str] | None = None, + partitioning_flavor: str | None = None, + schema: Schema | None = None, + filesystem: _SupportedFileSystem | str | None = None, + file_options: FileWriteOptions | None = None, + use_threads: bool | None = True, + max_partitions: int | None = None, + max_open_files: int | None = None, + max_rows_per_file: int | None = None, + min_rows_per_group: int | None = None, + max_rows_per_group: int | None = None, + file_visitor: Callable[[str], None] | None = None, + existing_data_behavior: Literal[ + "error", "overwrite_or_ignore", "delete_matching" + ] = "error", + create_dir: bool = True, + preserve_order: bool = False, +) -> None: ... +def _get_partition_keys(partition_expression: Expression) -> dict[str, Any]: ... diff --git a/python/pyarrow-stubs/parquet/__init__.pyi b/python/pyarrow-stubs/parquet/__init__.pyi new file mode 100644 index 000000000000..5329bd6c66af --- /dev/null +++ b/python/pyarrow-stubs/parquet/__init__.pyi @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from .core import * # noqa: F401, F403 diff --git a/python/pyarrow-stubs/parquet/core.pyi b/python/pyarrow-stubs/parquet/core.pyi new file mode 100644 index 000000000000..ff9cfc1fd776 --- /dev/null +++ b/python/pyarrow-stubs/parquet/core.pyi @@ -0,0 +1,361 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from collections.abc import Callable, Iterable, Iterator, Sequence +from pathlib import Path +from typing import IO, Any, Literal, Self, TypeAlias + +from pyarrow import _parquet +from pyarrow._compute import Expression +from pyarrow._fs import FileSystem, _SupportedFileSystem +from pyarrow._parquet import ( + ColumnChunkMetaData, + ColumnSchema, + FileDecryptionProperties, + FileEncryptionProperties, + FileMetaData, + ParquetLogicalType, + ParquetReader, + ParquetSchema, + RowGroupMetaData, + SortingColumn, + Statistics, +) +from pyarrow._stubs_typing import FilterTuple, SingleOrList +from pyarrow.dataset import ParquetFileFragment, Partitioning, PartitioningFactory +from pyarrow.lib import ( + Buffer, + ChunkedArray, + DataType, + NativeFile, + RecordBatch, + Schema, + Table, +) +from typing_extensions import deprecated + +__all__ = ( + "ColumnChunkMetaData", + "ColumnSchema", + "FileDecryptionProperties", + "FileEncryptionProperties", + "FileMetaData", + "ParquetDataset", + "ParquetFile", + "ParquetLogicalType", + "ParquetReader", + "ParquetSchema", + "ParquetWriter", + "RowGroupMetaData", + "SortingColumn", + "Statistics", + "read_metadata", + "read_pandas", + "read_schema", + "read_table", + "write_metadata", + "write_table", + "write_to_dataset", + "_filters_to_expression", + "filters_to_expression", +) + +def filters_to_expression( + filters: Sequence[FilterTuple] | Sequence[Sequence[FilterTuple]], +) -> Expression: ... +@deprecated("use filters_to_expression") +def _filters_to_expression( + filters: Sequence[FilterTuple] | Sequence[Sequence[FilterTuple]], +) -> Expression: ... + +_Compression: TypeAlias = Literal[ + "gzip", "bz2", "brotli", "lz4", "zstd", "snappy", "none" +] + +class ParquetFile: + reader: ParquetReader + common_metadata: FileMetaData + + def __init__( + self, + source: str | Path | Buffer | NativeFile | IO[Any], + *, + metadata: FileMetaData | None = None, + common_metadata: FileMetaData | None = None, + read_dictionary: list[str] | None = None, + binary_type: DataType | None = None, + list_type: DataType | None = None, + memory_map: bool = False, + buffer_size: int = 0, + pre_buffer: bool = False, + coerce_int96_timestamp_unit: str | None = None, + decryption_properties: FileDecryptionProperties | None = None, + thrift_string_size_limit: int | None = None, + thrift_container_size_limit: int | None = None, + filesystem: _SupportedFileSystem | None = None, + page_checksum_verification: bool = False, + arrow_extensions_enabled: bool = True, + ) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: object, **kwargs: Any) -> None: ... + @property + def metadata(self) -> FileMetaData: ... + @property + def schema(self) -> ParquetSchema: ... + @property + def schema_arrow(self) -> Schema: ... + @property + def num_row_groups(self) -> int: ... + def close(self, force: bool = False) -> None: ... + @property + def closed(self) -> bool: ... + def read_row_group( + self, + i: int, + columns: Sequence[str | int] | None = None, + use_threads: bool = True, + use_pandas_metadata: bool = False, + ) -> Table: ... + def read_row_groups( + self, + row_groups: Sequence[int], + columns: Iterable[str | int] | None = None, + use_threads: bool = True, + use_pandas_metadata: bool = False, + ) -> Table: ... + def iter_batches( + self, + batch_size: int = 65536, + row_groups: Sequence[int] | None = None, + columns: Iterable[str | int] | None = None, + use_threads: bool = True, + use_pandas_metadata: bool = False, + ) -> Iterator[RecordBatch]: ... + def read( + self, + columns: Sequence[str | int] | None = None, + use_threads: bool = True, + use_pandas_metadata: bool = False, + ) -> Table: ... + def scan_contents( + self, columns: Iterable[str | int] | None = None, batch_size: int = 65536 + ) -> int: ... + +class ParquetWriter: + flavor: str + schema_changed: bool + schema: ParquetSchema + where: str | Path | IO[Any] + file_handler: NativeFile | None + writer: _parquet.ParquetWriter + is_open: bool + + def __init__( + self, + where: str | Path | IO[Any] | NativeFile, + schema: Schema, + filesystem: _SupportedFileSystem | None = None, + flavor: str | None = None, + version: Literal["1.0", "2.4", "2.6"] = ..., + use_dictionary: bool = True, + compression: _Compression | dict[str, _Compression] = "snappy", + write_statistics: bool | list[str] = True, + use_deprecated_int96_timestamps: bool | None = None, + compression_level: int | dict[str, int] | None = None, + use_byte_stream_split: bool | list[str] = False, + column_encoding: str | dict[str, str] | None = None, + writer_engine_version: str | None = None, + data_page_version: Literal["1.0", "2.0"] = ..., + use_compliant_nested_type: bool = True, + encryption_properties: FileEncryptionProperties | None = None, + write_batch_size: int | None = None, + dictionary_pagesize_limit: int | None = None, + store_schema: bool = True, + write_page_index: bool = False, + write_page_checksum: bool = False, + sorting_columns: Sequence[SortingColumn] | None = None, + store_decimal_as_integer: bool = False, + write_time_adjusted_to_utc: bool = False, + max_rows_per_page: int | None = None, + **options: Any, + ) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: object, **kwargs: Any) -> Literal[False]: ... + def write( + self, table_or_batch: RecordBatch | Table, row_group_size: int | None = None + ) -> None: ... + def write_batch( + self, batch: RecordBatch, row_group_size: int | None = None + ) -> None: ... + def write_table(self, table: Table, row_group_size: int | None = None) -> None: ... + def close(self) -> None: ... + def add_key_value_metadata(self, key_value_metadata: dict[str, str]) -> None: ... + +class ParquetDataset: + def __init__( + self, + path_or_paths: SingleOrList[str] + | SingleOrList[Path] + | SingleOrList[NativeFile] + | SingleOrList[IO[Any]], + filesystem: _SupportedFileSystem | None = None, + schema: Schema | None = None, + *, + filters: Expression + | FilterTuple + | Sequence[FilterTuple] + | Sequence[Sequence[FilterTuple]] + | None = None, + read_dictionary: list[str] | None = None, + binary_type: DataType | None = None, + list_type: DataType | None = None, + memory_map: bool = False, + buffer_size: int | None = None, + partitioning: str + | list[str] + | Partitioning + | PartitioningFactory + | None = "hive", + ignore_prefixes: list[str] | None = None, + pre_buffer: bool = True, + coerce_int96_timestamp_unit: str | None = None, + decryption_properties: FileDecryptionProperties | None = None, + thrift_string_size_limit: int | None = None, + thrift_container_size_limit: int | None = None, + page_checksum_verification: bool = False, + arrow_extensions_enabled: bool = True, + ) -> None: ... + def equals(self, other: ParquetDataset) -> bool: ... + @property + def schema(self) -> Schema: ... + def read( + self, + columns: list[str] | None = None, + use_threads: bool = True, + use_pandas_metadata: bool = False, + ) -> Table: ... + def read_pandas(self, **kwargs: Any) -> Table: ... + @property + def fragments(self) -> list[ParquetFileFragment]: ... + @property + def files(self) -> list[str]: ... + @property + def filesystem(self) -> FileSystem: ... + @property + def partitioning(self) -> Partitioning: ... + +def read_table( + source: SingleOrList[str] + | SingleOrList[Path] + | SingleOrList[NativeFile] + | SingleOrList[IO[Any]] + | Buffer, + *, + columns: Sequence[str] | None = None, + use_threads: bool = True, + schema: Schema | None = None, + use_pandas_metadata: bool = False, + read_dictionary: list[str] | None = None, + binary_type: DataType | None = None, + list_type: DataType | None = None, + memory_map: bool = False, + buffer_size: int = 0, + partitioning: str | list[str] | Partitioning | PartitioningFactory | None = "hive", + filesystem: _SupportedFileSystem | str | None = None, + filters: Expression + | FilterTuple + | Sequence[FilterTuple] + | Sequence[Sequence[tuple[Any, ...]]] + | None = None, + ignore_prefixes: list[str] | None = None, + pre_buffer: bool = True, + coerce_int96_timestamp_unit: str | None = None, + decryption_properties: FileDecryptionProperties | None = None, + thrift_string_size_limit: int | None = None, + thrift_container_size_limit: int | None = None, + page_checksum_verification: bool = False, + arrow_extensions_enabled: bool = True, +) -> Table: ... +def read_pandas( + source: str | Path | NativeFile | IO[Any] | Buffer, + columns: Sequence[str] | None = None, + **kwargs: Any, +) -> Table: ... +def write_table( + table: Table, + where: str | Path | NativeFile | IO[Any], + row_group_size: int | None = None, + version: Literal["1.0", "2.4", "2.6"] = "2.6", + use_dictionary: bool = True, + compression: _Compression | dict[str, _Compression] = "snappy", + write_statistics: bool | list[str] = True, + use_deprecated_int96_timestamps: bool | None = None, + coerce_timestamps: str | None = None, + allow_truncated_timestamps: bool = False, + data_page_size: int | None = None, + flavor: str | None = None, + filesystem: _SupportedFileSystem | str | None = None, + compression_level: int | dict[str, int] | None = None, + use_byte_stream_split: bool = False, + column_encoding: str | dict[str, str] | None = None, + data_page_version: Literal["1.0", "2.0"] = ..., + use_compliant_nested_type: bool = True, + encryption_properties: FileEncryptionProperties | None = None, + write_batch_size: int | None = None, + dictionary_pagesize_limit: int | None = None, + store_schema: bool = True, + write_page_index: bool = False, + write_page_checksum: bool = False, + sorting_columns: Sequence[SortingColumn] | None = None, + store_decimal_as_integer: bool = False, + write_time_adjusted_to_utc: bool = False, + max_rows_per_page: int | None = None, + **kwargs: Any, +) -> None: ... +def write_to_dataset( + table: Table | ChunkedArray, + root_path: str | Path, + partition_cols: list[str] | None = None, + filesystem: _SupportedFileSystem | None = None, + schema: Schema | None = None, + partitioning: Partitioning | list[str] | None = None, + basename_template: str | None = None, + use_threads: bool | None = None, + file_visitor: Callable[[str], None] | None = None, + existing_data_behavior: Literal["overwrite_or_ignore", "error", "delete_matching"] + | None = None, + **kwargs: Any, +) -> None: ... +def write_metadata( + schema: Schema, + where: str | NativeFile, + metadata_collector: list[FileMetaData] | None = None, + filesystem: _SupportedFileSystem | None = None, + **kwargs: Any, +) -> None: ... +def read_metadata( + where: str | Path | IO[Any] | NativeFile, + memory_map: bool = False, + decryption_properties: FileDecryptionProperties | None = None, + filesystem: _SupportedFileSystem | str | None = None, +) -> FileMetaData: ... +def read_schema( + where: str | Path | IO[Any] | NativeFile, + memory_map: bool = False, + decryption_properties: FileDecryptionProperties | None = None, + filesystem: _SupportedFileSystem | str | None = None, +) -> Schema: ... diff --git a/python/pyarrow-stubs/parquet/encryption.pyi b/python/pyarrow-stubs/parquet/encryption.pyi new file mode 100644 index 000000000000..5c185494597f --- /dev/null +++ b/python/pyarrow-stubs/parquet/encryption.pyi @@ -0,0 +1,27 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from pyarrow._parquet_encryption import ( + CryptoFactory as CryptoFactory, + DecryptionConfiguration as DecryptionConfiguration, + EncryptionConfiguration as EncryptionConfiguration, + FileSystemKeyMaterialStore as FileSystemKeyMaterialStore, + KmsClient as KmsClient, + KmsConnectionConfig as KmsConnectionConfig, + create_decryption_properties as create_decryption_properties, + create_encryption_properties as create_encryption_properties, +) From a31718e95e69035de540563ebf7fcd5836d4279f Mon Sep 17 00:00:00 2001 From: Rok Mihevc Date: Mon, 30 Nov 2026 18:33:30 +0100 Subject: [PATCH 32/33] GH-49198: [Python][Annotations] Add type stubs for flight, cuda, interchange, and other modules --- .../pyarrow-stubs-tests/test_leaf_modules.py | 33 ++ python/pyarrow-stubs/__lib/compat.pyi | 22 + python/pyarrow-stubs/__lib/pandas_shim.pyi | 70 +++ python/pyarrow-stubs/_cuda.pyi | 118 ++++ python/pyarrow-stubs/_flight.pyi | 531 ++++++++++++++++++ python/pyarrow-stubs/_substrait.pyi | 57 ++ python/pyarrow-stubs/cffi.pyi | 21 + python/pyarrow-stubs/cuda.pyi | 42 ++ python/pyarrow-stubs/flight.pyi | 112 ++++ python/pyarrow-stubs/gandiva.pyi | 97 ++++ python/pyarrow-stubs/interchange/__init__.pyi | 20 + python/pyarrow-stubs/interchange/buffer.pyi | 40 ++ python/pyarrow-stubs/interchange/column.pyi | 84 +++ .../pyarrow-stubs/interchange/dataframe.pyi | 45 ++ .../interchange/from_dataframe.pyi | 71 +++ python/pyarrow-stubs/lib.pyi | 2 + python/pyarrow-stubs/pandas_compat.pyi | 76 +++ python/pyarrow-stubs/substrait.pyi | 38 ++ python/pyarrow-stubs/util.pyi | 56 ++ python/pyproject.toml | 15 +- 20 files changed, 1540 insertions(+), 10 deletions(-) create mode 100644 python/pyarrow-stubs-tests/test_leaf_modules.py create mode 100644 python/pyarrow-stubs/__lib/compat.pyi create mode 100644 python/pyarrow-stubs/__lib/pandas_shim.pyi create mode 100644 python/pyarrow-stubs/_cuda.pyi create mode 100644 python/pyarrow-stubs/_flight.pyi create mode 100644 python/pyarrow-stubs/_substrait.pyi create mode 100644 python/pyarrow-stubs/cffi.pyi create mode 100644 python/pyarrow-stubs/cuda.pyi create mode 100644 python/pyarrow-stubs/flight.pyi create mode 100644 python/pyarrow-stubs/gandiva.pyi create mode 100644 python/pyarrow-stubs/interchange/__init__.pyi create mode 100644 python/pyarrow-stubs/interchange/buffer.pyi create mode 100644 python/pyarrow-stubs/interchange/column.pyi create mode 100644 python/pyarrow-stubs/interchange/dataframe.pyi create mode 100644 python/pyarrow-stubs/interchange/from_dataframe.pyi create mode 100644 python/pyarrow-stubs/pandas_compat.pyi create mode 100644 python/pyarrow-stubs/substrait.pyi create mode 100644 python/pyarrow-stubs/util.pyi diff --git a/python/pyarrow-stubs-tests/test_leaf_modules.py b/python/pyarrow-stubs-tests/test_leaf_modules.py new file mode 100644 index 000000000000..1eb2e63ae28a --- /dev/null +++ b/python/pyarrow-stubs-tests/test_leaf_modules.py @@ -0,0 +1,33 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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 pyarrow as pa +import pyarrow.interchange as interchange +import pyarrow.util as pa_util + +from _check import assert_type, check + + +def test_interchange() -> None: + table = pa.table({"a": [1, 2, 3], "b": ["x", "y", "z"]}) + df_obj = table.__dataframe__() + roundtripped = interchange.from_dataframe(df_obj) + check(assert_type(roundtripped, pa.Table), pa.Table) + + +def test_util() -> None: + check(assert_type(pa_util.guid(), str), str) diff --git a/python/pyarrow-stubs/__lib/compat.pyi b/python/pyarrow-stubs/__lib/compat.pyi new file mode 100644 index 000000000000..8b720e87ea24 --- /dev/null +++ b/python/pyarrow-stubs/__lib/compat.pyi @@ -0,0 +1,22 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +def encode_file_path(path: str | bytes) -> bytes: ... +def tobytes(o: str | bytes) -> bytes: ... +def frombytes(o: bytes, *, safe: bool = False) -> str: ... + +__all__ = ["encode_file_path", "tobytes", "frombytes"] diff --git a/python/pyarrow-stubs/__lib/pandas_shim.pyi b/python/pyarrow-stubs/__lib/pandas_shim.pyi new file mode 100644 index 000000000000..c95e994cf9bf --- /dev/null +++ b/python/pyarrow-stubs/__lib/pandas_shim.pyi @@ -0,0 +1,70 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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 types as stdlib_types +from collections.abc import Iterable +from typing import Any, TypeGuard + +from pandas import Categorical, DatetimeTZDtype, Index, Series, DataFrame + +from numpy import dtype +from pandas.core.dtypes.base import ExtensionDtype + +class _PandasAPIShim: + has_sparse: bool + + def series(self, *args: Any, **kwargs: Any) -> Series: ... + def data_frame(self, *args: Any, **kwargs: Any) -> DataFrame: ... + @property + def have_pandas(self) -> bool: ... + @property + def compat(self) -> stdlib_types.ModuleType: ... + @property + def pd(self) -> stdlib_types.ModuleType: ... + def infer_dtype(self, obj: Iterable[Any]) -> str: ... + def pandas_dtype(self, dtype: str) -> dtype: ... + @property + def loose_version(self) -> Any: ... + @property + def version(self) -> str: ... + def is_v1(self) -> bool: ... + def is_ge_v21(self) -> bool: ... + def is_ge_v23(self) -> bool: ... + def is_ge_v3(self) -> bool: ... + def uses_string_dtype(self) -> bool: ... + @property + def categorical_type(self) -> type[Categorical]: ... + @property + def datetimetz_type(self) -> type[DatetimeTZDtype]: ... + @property + def extension_dtype(self) -> type[ExtensionDtype]: ... + def is_array_like( + self, obj: Any + ) -> TypeGuard[Series | Index | Categorical | ExtensionDtype]: ... + def is_categorical(self, obj: Any) -> TypeGuard[Categorical]: ... + def is_datetimetz(self, obj: Any) -> TypeGuard[DatetimeTZDtype]: ... + def is_extension_array_dtype(self, obj: Any) -> TypeGuard[ExtensionDtype]: ... + def is_sparse(self, obj: Any) -> bool: ... + def is_data_frame(self, obj: Any) -> TypeGuard[DataFrame]: ... + def is_series(self, obj: Any) -> TypeGuard[Series]: ... + def is_index(self, obj: Any) -> TypeGuard[Index]: ... + def get_values(self, obj: Any) -> bool: ... + def get_rangeindex_attribute(self, level: Any, name: str) -> Any: ... + +_pandas_api: _PandasAPIShim + +__all__ = ["_PandasAPIShim", "_pandas_api"] diff --git a/python/pyarrow-stubs/_cuda.pyi b/python/pyarrow-stubs/_cuda.pyi new file mode 100644 index 000000000000..84a66ff83ec7 --- /dev/null +++ b/python/pyarrow-stubs/_cuda.pyi @@ -0,0 +1,118 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from typing import Any + +import cuda +from numba.cuda.cudadrv import driver as _numba_driver +from numpy.typing import ArrayLike + +from . import lib + +class Context(lib._Weakrefable): + def __init__(self, device_number: int = 0, handle: int | None = None) -> None: ... + @staticmethod + def from_numba(context: _numba_driver.Context | None = None) -> Context: ... + def to_numba(self) -> _numba_driver.Context: ... + @staticmethod + def get_num_devices() -> int: ... + @property + def device_number(self) -> int: ... + @property + def handle(self) -> int: ... + def synchronize(self) -> None: ... + @property + def bytes_allocated(self) -> int: ... + def get_device_address(self, address: int) -> int: ... + def new_buffer(self, nbytes: int) -> CudaBuffer: ... + @property + def memory_manager(self) -> lib.MemoryManager: ... + @property + def device(self) -> lib.Device: ... + def foreign_buffer( + self, address: int, size: int, base: Any | None = None + ) -> CudaBuffer: ... + def open_ipc_buffer(self, ipc_handle: IpcMemHandle) -> CudaBuffer: ... + def buffer_from_data( + self, + data: CudaBuffer | HostBuffer | lib.Buffer | ArrayLike, + offset: int = 0, + size: int = -1, + ) -> CudaBuffer: ... + def buffer_from_object(self, obj: Any) -> CudaBuffer: ... + +class IpcMemHandle(lib._Weakrefable): + @staticmethod + def from_buffer(opaque_handle: lib.Buffer) -> IpcMemHandle: ... + def serialize(self, pool: lib.MemoryPool | None = None) -> lib.Buffer: ... + +class CudaBuffer(lib.Buffer): + @staticmethod + def from_buffer(buf: lib.Buffer) -> CudaBuffer: ... + @staticmethod + def from_numba(mem: _numba_driver.MemoryPointer) -> CudaBuffer: ... + def to_numba(self) -> _numba_driver.MemoryPointer: ... + def copy_to_host( + self, + position: int = 0, + nbytes: int = -1, + buf: lib.Buffer | None = None, + memory_pool: lib.MemoryPool | None = None, + resizable: bool = False, + ) -> lib.Buffer: ... + def copy_from_host( + self, data: lib.Buffer | ArrayLike, position: int = 0, nbytes: int = -1 + ) -> int: ... + def copy_from_device( + self, buf: CudaBuffer, position: int = 0, nbytes: int = -1 + ) -> int: ... + def export_for_ipc(self) -> IpcMemHandle: ... + @property + def context(self) -> Context: ... + def slice(self, offset: int = 0, length: int | None = None) -> CudaBuffer: ... + def to_pybytes(self) -> bytes: ... + +class HostBuffer(lib.Buffer): + @property + def size(self) -> int: ... + +class BufferReader(lib.NativeFile): + def __init__(self, obj: CudaBuffer) -> None: ... + def read_buffer(self, nbytes: int | None = None) -> CudaBuffer: ... + +class BufferWriter(lib.NativeFile): + def __init__(self, obj: CudaBuffer) -> None: ... + def writeat(self, position: int, data: ArrayLike) -> None: ... + @property + def buffer_size(self) -> int: ... + @buffer_size.setter + def buffer_size(self, buffer_size: int) -> None: ... + @property + def num_bytes_buffered(self) -> int: ... + +def new_host_buffer(size: int, device: int = 0) -> HostBuffer: ... +def serialize_record_batch(batch: lib.RecordBatch, ctx: Context) -> CudaBuffer: ... +def read_message( + source: CudaBuffer | cuda.BufferReader, pool: lib.MemoryManager | None = None +) -> lib.Message: ... +def read_record_batch( + buffer: lib.Buffer, + object: lib.Schema, + *, + dictionary_memo: lib.DictionaryMemo | None = None, + pool: lib.MemoryPool | None = None, +) -> lib.RecordBatch: ... diff --git a/python/pyarrow-stubs/_flight.pyi b/python/pyarrow-stubs/_flight.pyi new file mode 100644 index 000000000000..ce8cc0c008d2 --- /dev/null +++ b/python/pyarrow-stubs/_flight.pyi @@ -0,0 +1,531 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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 asyncio +import enum +from collections.abc import Iterable, Iterator, Sequence +from datetime import datetime +from typing import Any, Generic, NamedTuple, Self, TypeVar + +from typing_extensions import deprecated + +from .ipc import _ReadPandasMixin, ReadStats +from .lib import ( + ArrowCancelled, + ArrowException, + ArrowInvalid, + Buffer, + IpcReadOptions, + IpcWriteOptions, + RecordBatch, + RecordBatchReader, + Scalar, + Schema, + Table, + _CRecordBatchWriter, + _Weakrefable, +) + +_T = TypeVar("_T") + +class FlightCallOptions(_Weakrefable): + def __init__( + self, + timeout: float | None = None, + write_options: IpcWriteOptions | None = None, + headers: Sequence[tuple[str | bytes, str | bytes]] | None = None, + read_options: IpcReadOptions | None = None, + ) -> None: ... + @property + def timeout(self) -> float: ... + @property + def headers(self) -> list[tuple[bytes, bytes]]: ... + @property + def read_options(self) -> IpcReadOptions: ... + @property + def write_options(self) -> IpcWriteOptions: ... + +class CertKeyPair(NamedTuple): + cert: str | bytes | None + key: str | bytes | None + +class FlightError(Exception): + extra_info: bytes + +class FlightInternalError(FlightError, ArrowException): ... +class FlightTimedOutError(FlightError, ArrowException): ... + +class FlightCancelledError(FlightError, ArrowCancelled): + def __init__(self, message: str, *, extra_info: bytes | None = None) -> None: ... + +class FlightServerError(FlightError, ArrowException): ... +class FlightUnauthenticatedError(FlightError, ArrowException): ... +class FlightUnauthorizedError(FlightError, ArrowException): ... +class FlightUnavailableError(FlightError, ArrowException): ... + +class FlightWriteSizeExceededError(ArrowInvalid): + limit: int + actual: int + def __init__(self, message: str, limit: int, actual: int) -> None: ... + +class Action(_Weakrefable): + def __init__( + self, action_type: bytes | str, buf: Buffer | bytes | None + ) -> None: ... + @property + def type(self) -> str: ... + @property + def body(self) -> Buffer: ... + def serialize(self) -> bytes: ... + @classmethod + def deserialize(cls, serialized: bytes) -> Self: ... + +class ActionType(NamedTuple): + type: str + description: str + + def make_action(self, buf: Buffer | bytes) -> Action: ... + +class Result(_Weakrefable): + def __init__(self, buf: Buffer | bytes) -> None: ... + @property + def body(self) -> Buffer: ... + def serialize(self) -> bytes: ... + @classmethod + def deserialize(cls, serialized: bytes) -> Self: ... + +class BasicAuth(_Weakrefable): + def __init__( + self, username: str | bytes | None = None, password: str | bytes | None = None + ) -> None: ... + @property + def username(self) -> bytes: ... + @property + def password(self) -> bytes: ... + def serialize(self) -> str: ... + @staticmethod + def deserialize(serialized: str | bytes) -> BasicAuth: ... + +class DescriptorType(enum.Enum): + UNKNOWN = 0 + PATH = 1 + CMD = 2 + +class FlightMethod(enum.Enum): + INVALID = 0 + HANDSHAKE = 1 + LIST_FLIGHTS = 2 + GET_FLIGHT_INFO = 3 + GET_SCHEMA = 4 + DO_GET = 5 + DO_PUT = 6 + DO_ACTION = 7 + LIST_ACTIONS = 8 + DO_EXCHANGE = 9 + +class FlightDescriptor(_Weakrefable): + @staticmethod + def for_path(*path: str | bytes) -> FlightDescriptor: ... + @staticmethod + def for_command(command: str | bytes) -> FlightDescriptor: ... + @property + def descriptor_type(self) -> DescriptorType: ... + @property + def path(self) -> list[bytes] | None: ... + @property + def command(self) -> bytes | None: ... + def serialize(self) -> bytes: ... + @classmethod + def deserialize(cls, serialized: bytes) -> Self: ... + +class Ticket(_Weakrefable): + def __init__(self, ticket: str | bytes) -> None: ... + @property + def ticket(self) -> bytes: ... + def serialize(self) -> bytes: ... + @classmethod + def deserialize(cls, serialized: bytes) -> Self: ... + +class Location(_Weakrefable): + def __init__(self, uri: str | bytes) -> None: ... + @property + def uri(self) -> bytes: ... + def equals(self, other: Location) -> bool: ... + @staticmethod + def for_grpc_tcp(host: str | bytes, port: int) -> Location: ... + @staticmethod + def for_grpc_tls(host: str | bytes, port: int) -> Location: ... + @staticmethod + def for_grpc_unix(path: str | bytes) -> Location: ... + +class FlightEndpoint(_Weakrefable): + def __init__( + self, + ticket: Ticket | str | bytes | object, + locations: Sequence[str | bytes | Location | object], + expiration_time: Scalar | str | datetime | None = ..., + app_metadata: bytes | str | object = ..., + ) -> None: ... + @property + def ticket(self) -> Ticket: ... + @property + def locations(self) -> list[Location]: ... + def serialize(self) -> bytes: ... + @property + def expiration_time(self) -> Scalar | None: ... + @property + def app_metadata(self) -> bytes | str: ... + @classmethod + def deserialize(cls, serialized: bytes) -> Self: ... + +class SchemaResult(_Weakrefable): + def __init__(self, schema: Schema) -> None: ... + @property + def schema(self) -> Schema: ... + def serialize(self) -> bytes: ... + @classmethod + def deserialize(cls, serialized: bytes) -> Self: ... + +class FlightInfo(_Weakrefable): + def __init__( + self, + schema: Schema | None, + descriptor: FlightDescriptor, + endpoints: list[FlightEndpoint], + total_records: int | None = ..., + total_bytes: int | None = ..., + ordered: bool = ..., + app_metadata: bytes | str = ..., + ) -> None: ... + @property + def schema(self) -> Schema | None: ... + @property + def descriptor(self) -> FlightDescriptor: ... + @property + def endpoints(self) -> list[FlightEndpoint]: ... + @property + def total_records(self) -> int: ... + @property + def total_bytes(self) -> int: ... + @property + def ordered(self) -> bool: ... + @property + def app_metadata(self) -> bytes | str: ... + def serialize(self) -> bytes: ... + @classmethod + def deserialize(cls, serialized: bytes) -> Self: ... + +class FlightStreamChunk(_Weakrefable): + @property + def data(self) -> RecordBatch | None: ... + @property + def app_metadata(self) -> Buffer | None: ... + def __iter__(self) -> Iterator[RecordBatch | Buffer | None]: ... + +class _MetadataRecordBatchReader(_Weakrefable, _ReadPandasMixin): + # Needs to be separate class so the "real" class can subclass the + # pure-Python mixin class + + def __iter__(self) -> Self: ... + def __next__(self) -> FlightStreamChunk: ... + @property + def schema(self) -> Schema: ... + def read_all(self) -> Table: ... + def read_chunk(self) -> FlightStreamChunk: ... + def to_reader(self) -> RecordBatchReader: ... + +class MetadataRecordBatchReader(_MetadataRecordBatchReader): + @property + def stats(self) -> ReadStats: ... + +class FlightStreamReader(MetadataRecordBatchReader): + @property + def stats(self) -> ReadStats: ... + def cancel(self) -> None: ... + def read_all(self) -> Table: ... + +class MetadataRecordBatchWriter(_CRecordBatchWriter): + def begin(self, schema: Schema, options: IpcWriteOptions | None = None) -> None: ... + def write_metadata(self, buf: Buffer | bytes) -> None: ... + def write_batch(self, batch: RecordBatch) -> None: ... # type: ignore[override] + def write_table( + self, table: Table, max_chunksize: int | None = None, **kwargs: Any + ) -> None: ... + def close(self) -> None: ... + def write_with_metadata(self, batch: RecordBatch, buf: Buffer | bytes) -> None: ... + +class FlightStreamWriter(MetadataRecordBatchWriter): + def done_writing(self) -> None: ... + +class FlightMetadataReader(_Weakrefable): + def read(self) -> Buffer | None: ... + +class FlightMetadataWriter(_Weakrefable): + def write(self, message: Buffer) -> None: ... + +class AsyncioCall(Generic[_T]): + _future: asyncio.Future[_T] + + def as_awaitable(self) -> asyncio.Future[_T]: ... + def wakeup(self, result_or_exception: BaseException | _T) -> None: ... + +class AsyncioFlightClient: + def __init__(self, client: FlightClient) -> None: ... + async def get_flight_info( + self, + descriptor: FlightDescriptor, + *, + options: FlightCallOptions | None = None, + ) -> FlightInfo: ... + +class FlightClient(_Weakrefable): + def __init__( + self, + location: str | tuple[str, int] | Location, + *, + tls_root_certs: str | None = None, + cert_chain: str | None = None, + private_key: str | None = None, + override_hostname: str | None = None, + middleware: list[ClientMiddlewareFactory] | None = None, + write_size_limit_bytes: int | None = None, + disable_server_verification: bool | None = None, + generic_options: Sequence[tuple[str, int | str]] | None = None, + ) -> None: ... + @property + def supports_async(self) -> bool: ... + def as_async(self) -> AsyncioFlightClient: ... + def wait_for_available(self, timeout: int = 5) -> None: ... + @classmethod + @deprecated( + "Use the ``FlightClient`` constructor or " + "``pyarrow.flight.connect`` function instead." + ) + def connect( + cls, + location: str | tuple[str, int] | Location, + tls_root_certs: str | None = None, + cert_chain: str | None = None, + private_key: str | None = None, + override_hostname: str | None = None, + disable_server_verification: bool | None = None, + ) -> FlightClient: ... + def authenticate( + self, auth_handler: ClientAuthHandler, options: FlightCallOptions | None = None + ) -> None: ... + def authenticate_basic_token( + self, + username: str | bytes, + password: str | bytes, + options: FlightCallOptions | None = None, + ) -> tuple[str, str]: ... + def list_actions( + self, options: FlightCallOptions | None = None + ) -> list[Action]: ... + def do_action( + self, + action: Action | tuple[bytes | str, bytes | str] | str, + options: FlightCallOptions | None = None, + ) -> Iterator[Result]: ... + def list_flights( + self, + criteria: str | bytes | None = None, + options: FlightCallOptions | None = None, + ) -> Iterator[FlightInfo]: ... + def get_flight_info( + self, descriptor: FlightDescriptor, options: FlightCallOptions | None = None + ) -> FlightInfo: ... + def get_schema( + self, descriptor: FlightDescriptor, options: FlightCallOptions | None = None + ) -> SchemaResult: ... + def do_get( + self, ticket: Ticket, options: FlightCallOptions | None = None + ) -> FlightStreamReader: ... + def do_put( + self, + descriptor: FlightDescriptor, + schema: Schema | None, + options: FlightCallOptions | None = None, + ) -> tuple[FlightStreamWriter, FlightStreamReader]: ... + def do_exchange( + self, descriptor: FlightDescriptor, options: FlightCallOptions | None = None + ) -> tuple[FlightStreamWriter, FlightStreamReader]: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: object, exc_value: object, traceback: object + ) -> None: ... + +class FlightDataStream(_Weakrefable): ... + +class RecordBatchStream(FlightDataStream): + def __init__( + self, + data_source: RecordBatchReader | Table | None = None, + options: IpcWriteOptions | None = None, + ) -> None: ... + +class GeneratorStream(FlightDataStream): + def __init__( + self, + schema: Schema, + generator: Iterable[ + FlightDataStream + | Table + | RecordBatch + | RecordBatchReader + | tuple[RecordBatch, bytes] + ], + options: IpcWriteOptions | None = None, + ) -> None: ... + +class ServerCallContext(_Weakrefable): + def peer_identity(self) -> bytes: ... + def peer(self) -> str: ... + + # Set safe=True as gRPC on Windows sometimes gives garbage bytes + def is_cancelled(self) -> bool: ... + def add_header(self, key: str, value: str) -> None: ... + def add_trailer(self, key: str, value: str) -> None: ... + def get_middleware(self, key: str) -> ServerMiddleware | None: ... + +class ServerAuthReader(_Weakrefable): + def read(self) -> str: ... + +class ServerAuthSender(_Weakrefable): + def write(self, message: str) -> None: ... + +class ClientAuthReader(_Weakrefable): + def read(self) -> str: ... + +class ClientAuthSender(_Weakrefable): + def write(self, message: str) -> None: ... + +class ServerAuthHandler(_Weakrefable): + def authenticate( + self, outgoing: ServerAuthSender, incoming: ServerAuthReader + ) -> None: ... + def is_valid(self, token: str) -> bool: ... + +class ClientAuthHandler(_Weakrefable): + def authenticate( + self, outgoing: ClientAuthSender, incoming: ClientAuthReader + ) -> None: ... + def get_token(self) -> str: ... + +class CallInfo(NamedTuple): + method: FlightMethod + +class ClientMiddlewareFactory(_Weakrefable): + def start_call(self, info: CallInfo) -> ClientMiddleware | None: ... + +class ClientMiddleware(_Weakrefable): + def sending_headers(self) -> dict[str, list[str] | list[bytes]]: ... + def received_headers(self, headers: dict[str, list[str] | list[bytes]]) -> None: ... + def call_completed(self, exception: ArrowException) -> None: ... + +class ServerMiddlewareFactory(_Weakrefable): + def start_call( + self, info: CallInfo, headers: dict[str, list[str] | list[bytes]] + ) -> ServerMiddleware | None: ... + +class TracingServerMiddlewareFactory(ServerMiddlewareFactory): ... + +class ServerMiddleware(_Weakrefable): + def sending_headers(self) -> dict[str, list[str] | list[bytes]]: ... + def call_completed(self, exception: ArrowException) -> None: ... + +class TracingServerMiddleware(ServerMiddleware): + trace_context: dict[str, Any] + def __init__(self, trace_context: dict[str, Any]) -> None: ... + +class _ServerMiddlewareFactoryWrapper(ServerMiddlewareFactory): + def __init__(self, factories: dict[str, ServerMiddlewareFactory]) -> None: ... + def start_call( # type: ignore[override] + self, info: CallInfo, headers: dict[str, list[str] | list[bytes]] + ) -> _ServerMiddlewareFactoryWrapper | None: ... + +class _ServerMiddlewareWrapper(ServerMiddleware): + def __init__(self, middleware: dict[str, ServerMiddleware]) -> None: ... + def call_completed(self, exception: ArrowException) -> None: ... + +class _FlightServerFinalizer(_Weakrefable): + def finalize(self) -> None: ... + +class FlightServerBase(_Weakrefable): + def __init__( + self, + location: str | tuple[str, int] | Location | None = None, + auth_handler: ServerAuthHandler | None = None, + tls_certificates: list[tuple[str, str]] | None = None, + verify_client: bool = False, + root_certificates: str | None = None, + middleware: dict[str, ServerMiddlewareFactory] | None = None, + ) -> None: ... + @property + def port(self) -> int: ... + def list_flights( + self, context: ServerCallContext, criteria: str + ) -> Iterator[FlightInfo]: ... + def get_flight_info( + self, context: ServerCallContext, descriptor: FlightDescriptor + ) -> FlightInfo: ... + def get_schema( + self, context: ServerCallContext, descriptor: FlightDescriptor + ) -> Schema: ... + def do_put( + self, + context: ServerCallContext, + descriptor: FlightDescriptor, + reader: MetadataRecordBatchReader, + writer: FlightMetadataWriter, + ) -> None: ... + def do_get( + self, context: ServerCallContext, ticket: Ticket + ) -> FlightDataStream: ... + def do_exchange( + self, + context: ServerCallContext, + descriptor: FlightDescriptor, + reader: MetadataRecordBatchReader, + writer: MetadataRecordBatchWriter, + ) -> None: ... + def list_actions(self, context: ServerCallContext) -> Iterable[Action]: ... + def do_action( + self, context: ServerCallContext, action: Action + ) -> Iterable[bytes]: ... + def serve(self) -> None: ... + def run(self) -> None: ... + def shutdown(self) -> None: ... + def wait(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: object, exc_value: object, traceback: object + ) -> None: ... + +def connect( + location: str | tuple[str, int] | Location, + *, + tls_root_certs: str | None = None, + cert_chain: str | None = None, + private_key: str | None = None, + override_hostname: str | None = None, + middleware: list[ClientMiddlewareFactory] | None = None, + write_size_limit_bytes: int | None = None, + disable_server_verification: bool = False, + generic_options: Sequence[tuple[str, int | str]] | None = None, +) -> FlightClient: ... diff --git a/python/pyarrow-stubs/_substrait.pyi b/python/pyarrow-stubs/_substrait.pyi new file mode 100644 index 000000000000..dc1cc5664cbf --- /dev/null +++ b/python/pyarrow-stubs/_substrait.pyi @@ -0,0 +1,57 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from collections.abc import Callable +from typing import Any + +from ._compute import Expression +from .lib import Buffer, RecordBatchReader, Schema, Table, _Weakrefable + +def run_query( + plan: Buffer | int, + *, + table_provider: Callable[[list[str], Schema], Table] | None = None, + use_threads: bool = True, +) -> RecordBatchReader: ... +def _parse_json_plan(plan: bytes) -> Buffer: ... + +class SubstraitSchema: + schema: bytes + expression: bytes + def __init__(self, schema: bytes, expression: bytes) -> None: ... + def to_pysubstrait(self) -> Any: ... + +def serialize_schema(schema: Schema) -> SubstraitSchema: ... +def deserialize_schema(buf: Buffer | bytes | SubstraitSchema) -> Schema: ... +def serialize_expressions( + exprs: list[Expression], + names: list[str], + schema: Schema, + *, + allow_arrow_extensions: bool = False, +) -> Buffer: ... + +class BoundExpressions(_Weakrefable): + @property + def schema(self) -> Schema: ... + @property + def expressions(self) -> dict[str, Expression]: ... + @classmethod + def from_substrait(cls, message: Buffer | bytes | Any) -> BoundExpressions: ... + +def deserialize_expressions(buf: Buffer | bytes) -> BoundExpressions: ... +def get_supported_functions() -> list[str]: ... diff --git a/python/pyarrow-stubs/cffi.pyi b/python/pyarrow-stubs/cffi.pyi new file mode 100644 index 000000000000..e4f077d7155b --- /dev/null +++ b/python/pyarrow-stubs/cffi.pyi @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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 cffi + +c_source: str +ffi: cffi.FFI diff --git a/python/pyarrow-stubs/cuda.pyi b/python/pyarrow-stubs/cuda.pyi new file mode 100644 index 000000000000..0394965bb738 --- /dev/null +++ b/python/pyarrow-stubs/cuda.pyi @@ -0,0 +1,42 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from pyarrow._cuda import ( + BufferReader, + BufferWriter, + Context, + CudaBuffer, + HostBuffer, + IpcMemHandle, + new_host_buffer, + read_message, + read_record_batch, + serialize_record_batch, +) + +__all__ = [ + "BufferReader", + "BufferWriter", + "Context", + "CudaBuffer", + "HostBuffer", + "IpcMemHandle", + "new_host_buffer", + "read_message", + "read_record_batch", + "serialize_record_batch", +] diff --git a/python/pyarrow-stubs/flight.pyi b/python/pyarrow-stubs/flight.pyi new file mode 100644 index 000000000000..dcc6ee2244b3 --- /dev/null +++ b/python/pyarrow-stubs/flight.pyi @@ -0,0 +1,112 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from pyarrow._flight import ( + Action, + ActionType, + BasicAuth, + CallInfo, + CertKeyPair, + ClientAuthHandler, + ClientMiddleware, + ClientMiddlewareFactory, + DescriptorType, + FlightCallOptions, + FlightCancelledError, + FlightClient, + FlightDataStream, + FlightDescriptor, + FlightEndpoint, + FlightError, + FlightInfo, + FlightInternalError, + FlightMetadataReader, + FlightMetadataWriter, + FlightMethod, + FlightServerBase, + FlightServerError, + FlightStreamChunk, + FlightStreamReader, + FlightStreamWriter, + FlightTimedOutError, + FlightUnauthenticatedError, + FlightUnauthorizedError, + FlightUnavailableError, + FlightWriteSizeExceededError, + GeneratorStream, + Location, + MetadataRecordBatchReader, + MetadataRecordBatchWriter, + RecordBatchStream, + Result, + SchemaResult, + ServerAuthHandler, + ServerCallContext, + ServerMiddleware, + ServerMiddlewareFactory, + Ticket, + TracingServerMiddlewareFactory, + connect, +) + +__all__ = [ + "Action", + "ActionType", + "BasicAuth", + "CallInfo", + "CertKeyPair", + "ClientAuthHandler", + "ClientMiddleware", + "ClientMiddlewareFactory", + "DescriptorType", + "FlightCallOptions", + "FlightCancelledError", + "FlightClient", + "FlightDataStream", + "FlightDescriptor", + "FlightEndpoint", + "FlightError", + "FlightInfo", + "FlightInternalError", + "FlightMetadataReader", + "FlightMetadataWriter", + "FlightMethod", + "FlightServerBase", + "FlightServerError", + "FlightStreamChunk", + "FlightStreamReader", + "FlightStreamWriter", + "FlightTimedOutError", + "FlightUnauthenticatedError", + "FlightUnauthorizedError", + "FlightUnavailableError", + "FlightWriteSizeExceededError", + "GeneratorStream", + "Location", + "MetadataRecordBatchReader", + "MetadataRecordBatchWriter", + "RecordBatchStream", + "Result", + "SchemaResult", + "ServerAuthHandler", + "ServerCallContext", + "ServerMiddleware", + "ServerMiddlewareFactory", + "Ticket", + "TracingServerMiddlewareFactory", + "connect", +] diff --git a/python/pyarrow-stubs/gandiva.pyi b/python/pyarrow-stubs/gandiva.pyi new file mode 100644 index 000000000000..0fae64c15006 --- /dev/null +++ b/python/pyarrow-stubs/gandiva.pyi @@ -0,0 +1,97 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from collections.abc import Iterable, Sequence +from typing import Any, Literal + +from .lib import Array, DataType, Field, MemoryPool, RecordBatch, Schema, _Weakrefable + +class Node(_Weakrefable): + def return_type(self) -> DataType: ... + +class Expression(_Weakrefable): + def root(self) -> Node: ... + def result(self) -> Field: ... + +class Condition(_Weakrefable): + def root(self) -> Node: ... + def result(self) -> Field: ... + +class SelectionVector(_Weakrefable): + def to_array(self) -> Array: ... + +class Projector(_Weakrefable): + @property + def llvm_ir(self) -> str: ... + def evaluate( + self, batch: RecordBatch, selection: SelectionVector | None = None + ) -> list[Array]: ... + +class Filter(_Weakrefable): + @property + def llvm_ir(self) -> str: ... + def evaluate( + self, batch: RecordBatch, pool: MemoryPool, dtype: DataType | str = "int32" + ) -> SelectionVector: ... + +class TreeExprBuilder(_Weakrefable): + def make_literal( + self, value: float | str | bytes | bool, dtype: DataType | str | None + ) -> Node: ... + def make_expression( + self, root_node: Node | None, return_field: Field + ) -> Expression: ... + def make_function( + self, name: str, children: Sequence[Node | None], return_type: DataType + ) -> Node: ... + def make_field(self, field: Field | None) -> Node: ... + def make_if( + self, + condition: Node, + this_node: Node | None, + else_node: Node | None, + return_type: DataType | None, + ) -> Node: ... + def make_and(self, children: Sequence[Node | None]) -> Node: ... + def make_or(self, children: Sequence[Node | None]) -> Node: ... + def make_in_expression( + self, node: Node | None, values: Iterable[Any], dtype: DataType + ) -> Node: ... + def make_condition(self, condition: Node | None) -> Condition: ... + +class Configuration(_Weakrefable): + def __init__(self, optimize: bool = True, dump_ir: bool = False) -> None: ... + +def make_projector( + schema: Schema, + children: Sequence[Expression | None], + pool: MemoryPool | None = None, + selection_mode: Literal["NONE", "UINT16", "UINT32", "UINT64"] = "NONE", + configuration: Configuration | None = None, +) -> Projector: ... +def make_filter( + schema: Schema, + condition: Condition | None, + configuration: Configuration | None = None, +) -> Filter: ... + +class FunctionSignature(_Weakrefable): + def return_type(self) -> DataType: ... + def param_types(self) -> list[DataType]: ... + def name(self) -> str: ... + +def get_registered_function_signatures() -> list[FunctionSignature]: ... diff --git a/python/pyarrow-stubs/interchange/__init__.pyi b/python/pyarrow-stubs/interchange/__init__.pyi new file mode 100644 index 000000000000..fd5ae83c5692 --- /dev/null +++ b/python/pyarrow-stubs/interchange/__init__.pyi @@ -0,0 +1,20 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from .from_dataframe import from_dataframe as from_dataframe + +__all__ = ["from_dataframe"] diff --git a/python/pyarrow-stubs/interchange/buffer.pyi b/python/pyarrow-stubs/interchange/buffer.pyi new file mode 100644 index 000000000000..403784bc28ad --- /dev/null +++ b/python/pyarrow-stubs/interchange/buffer.pyi @@ -0,0 +1,40 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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 enum + +from pyarrow.lib import Buffer +from typing_extensions import CapsuleType + +class DlpackDeviceType(enum.IntEnum): + CPU = 1 + CUDA = 2 + CPU_PINNED = 3 + OPENCL = 4 + VULKAN = 7 + METAL = 8 + VPI = 9 + ROCM = 10 + +class _PyArrowBuffer: + def __init__(self, x: Buffer, allow_copy: bool = True) -> None: ... + @property + def bufsize(self) -> int: ... + @property + def ptr(self) -> int: ... + def __dlpack__(self) -> CapsuleType: ... + def __dlpack_device__(self) -> tuple[DlpackDeviceType, int | None]: ... diff --git a/python/pyarrow-stubs/interchange/column.pyi b/python/pyarrow-stubs/interchange/column.pyi new file mode 100644 index 000000000000..969a66f676fc --- /dev/null +++ b/python/pyarrow-stubs/interchange/column.pyi @@ -0,0 +1,84 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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 enum + +from collections.abc import Iterable +from typing import Any, TypeAlias, TypedDict + +from pyarrow.lib import Array, ChunkedArray + +from .buffer import _PyArrowBuffer + +class DtypeKind(enum.IntEnum): + INT = 0 + UINT = 1 + FLOAT = 2 + BOOL = 20 + STRING = 21 # UTF-8 + DATETIME = 22 + CATEGORICAL = 23 + +Dtype: TypeAlias = tuple[DtypeKind, int, str, str] + +class ColumnNullType(enum.IntEnum): + NON_NULLABLE = 0 + USE_NAN = 1 + USE_SENTINEL = 2 + USE_BITMASK = 3 + USE_BYTEMASK = 4 + +class ColumnBuffers(TypedDict): + data: tuple[_PyArrowBuffer, Dtype] + validity: tuple[_PyArrowBuffer, Dtype] | None + offsets: tuple[_PyArrowBuffer, Dtype] | None + +class CategoricalDescription(TypedDict): + is_ordered: bool + is_dictionary: bool + categories: _PyArrowColumn | None + +class Endianness(enum.Enum): + LITTLE = "<" + BIG = ">" + NATIVE = "=" + NA = "|" + +class NoBufferPresent(Exception): ... + +class _PyArrowColumn: + _col: Array | ChunkedArray + + def __init__( + self, column: Array | ChunkedArray, allow_copy: bool = True + ) -> None: ... + def size(self) -> int: ... + @property + def offset(self) -> int: ... + @property + def dtype(self) -> tuple[DtypeKind, int, str, str]: ... + @property + def describe_categorical(self) -> CategoricalDescription: ... + @property + def describe_null(self) -> tuple[ColumnNullType, Any]: ... + @property + def null_count(self) -> int: ... + @property + def metadata(self) -> dict[str, Any]: ... + def num_chunks(self) -> int: ... + def get_chunks(self, n_chunks: int | None = None) -> Iterable[_PyArrowColumn]: ... + def get_buffers(self) -> ColumnBuffers: ... diff --git a/python/pyarrow-stubs/interchange/dataframe.pyi b/python/pyarrow-stubs/interchange/dataframe.pyi new file mode 100644 index 000000000000..642e3945325d --- /dev/null +++ b/python/pyarrow-stubs/interchange/dataframe.pyi @@ -0,0 +1,45 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from collections.abc import Iterable, Sequence +from typing import Any, Self + +from pyarrow.interchange.column import _PyArrowColumn +from pyarrow.lib import RecordBatch, Table + +class _PyArrowDataFrame: + def __init__( + self, + df: Table | RecordBatch, + nan_as_null: bool = False, + allow_copy: bool = True, + ) -> None: ... + def __dataframe__( + self, nan_as_null: bool = False, allow_copy: bool = True + ) -> _PyArrowDataFrame: ... + @property + def metadata(self) -> dict[str, Any]: ... + def num_columns(self) -> int: ... + def num_rows(self) -> int: ... + def num_chunks(self) -> int: ... + def column_names(self) -> Iterable[str]: ... + def get_column(self, i: int) -> _PyArrowColumn: ... + def get_column_by_name(self, name: str) -> _PyArrowColumn: ... + def get_columns(self) -> Iterable[_PyArrowColumn]: ... + def select_columns(self, indices: Sequence[int]) -> Self: ... + def select_columns_by_name(self, names: Sequence[str]) -> Self: ... + def get_chunks(self, n_chunks: int | None = None) -> Iterable[Self]: ... diff --git a/python/pyarrow-stubs/interchange/from_dataframe.pyi b/python/pyarrow-stubs/interchange/from_dataframe.pyi new file mode 100644 index 000000000000..2eda94b966cd --- /dev/null +++ b/python/pyarrow-stubs/interchange/from_dataframe.pyi @@ -0,0 +1,71 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from typing import Any, Protocol, TypeAlias + +from pyarrow.lib import Array, Buffer, DataType, DictionaryArray, RecordBatch, Table + +from .column import ( + ColumnBuffers, + ColumnNullType, + Dtype, + DtypeKind, +) + +class DataFrameObject(Protocol): + def __dataframe__( + self, nan_as_null: bool = False, allow_copy: bool = True + ) -> Any: ... + +ColumnObject: TypeAlias = Any + +def from_dataframe(df: DataFrameObject, allow_copy: bool = True) -> Table: ... +def _from_dataframe(df: DataFrameObject, allow_copy: bool = True) -> Table: ... +def protocol_df_chunk_to_pyarrow( + df: DataFrameObject, allow_copy: bool = True +) -> RecordBatch: ... +def column_to_array(col: ColumnObject, allow_copy: bool = True) -> Array: ... +def bool_column_to_array(col: ColumnObject, allow_copy: bool = True) -> Array: ... +def categorical_column_to_dictionary( + col: ColumnObject, allow_copy: bool = True +) -> DictionaryArray: ... +def parse_datetime_format_str(format_str: str) -> tuple[str, str]: ... +def map_date_type(data_type: tuple[DtypeKind, int, str, str]) -> DataType: ... +def buffers_to_array( + buffers: ColumnBuffers, + data_type: tuple[DtypeKind, int, str, str], + length: int, + describe_null: ColumnNullType, + offset: int = 0, + allow_copy: bool = True, +) -> Array: ... +def validity_buffer_from_mask( + validity_buff: Buffer, + validity_dtype: Dtype, + describe_null: ColumnNullType, + length: int, + offset: int = 0, + allow_copy: bool = True, +) -> Buffer: ... +def validity_buffer_nan_sentinel( + data_pa_buffer: Buffer, + data_type: Dtype, + describe_null: ColumnNullType, + length: int, + offset: int = 0, + allow_copy: bool = True, +) -> Buffer: ... diff --git a/python/pyarrow-stubs/lib.pyi b/python/pyarrow-stubs/lib.pyi index 6f656fff5944..2aac2518ba71 100644 --- a/python/pyarrow-stubs/lib.pyi +++ b/python/pyarrow-stubs/lib.pyi @@ -23,12 +23,14 @@ from typing import Any, Self, final from pyarrow.__lib.array import * # noqa: F401,F403 from pyarrow.__lib.builder import * # noqa: F401,F403 +from pyarrow.__lib.compat import * # noqa: F401,F403 from pyarrow.__lib.config import * # noqa: F401,F403 from pyarrow.__lib.device import * # noqa: F401,F403 from pyarrow.__lib.error import * # noqa: F401,F403 from pyarrow.__lib.io import * # noqa: F401,F403 from pyarrow.__lib.ipc import * # noqa: F401,F403 from pyarrow.__lib.memory import * # noqa: F401,F403 +from pyarrow.__lib.pandas_shim import * # noqa: F401,F403 from pyarrow.__lib.scalar import * # noqa: F401,F403 from pyarrow.__lib.table import * # noqa: F401,F403 from pyarrow.__lib.tensor import * # noqa: F401,F403 diff --git a/python/pyarrow-stubs/pandas_compat.pyi b/python/pyarrow-stubs/pandas_compat.pyi new file mode 100644 index 000000000000..e66c553e7929 --- /dev/null +++ b/python/pyarrow-stubs/pandas_compat.pyi @@ -0,0 +1,76 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from typing import Any, TypedDict, TypeVar + +import numpy as np +import pandas as pd + +from pandas import DatetimeTZDtype + +from .lib import Array, DataType, Schema, Table, _pandas_api as _pandas_api + +_T = TypeVar("_T") + +def get_logical_type_map() -> dict[int, str]: ... +def get_logical_type(arrow_type: DataType) -> str: ... +def get_numpy_logical_type_map() -> dict[type[np.generic], str]: ... +def get_logical_type_from_numpy(pandas_collection: Any) -> str: ... +def get_extension_dtype_info(column: Any) -> tuple[str, dict[str, Any]]: ... + +class _ColumnMetadata(TypedDict): + name: str + field_name: str + pandas_type: int + numpy_type: str + metadata: dict[str, Any] | None + +def get_column_metadata( + column: pd.Series | pd.Index, name: str, arrow_type: DataType, field_name: str +) -> _ColumnMetadata: ... +def construct_metadata( + columns_to_convert: list[pd.Series], + df: pd.DataFrame, + column_names: list[str], + index_levels: list[pd.Index], + index_descriptors: list[dict[str, Any]], + preserve_index: bool, + types: list[DataType], + column_field_names: list[str] | None = None, +) -> dict[bytes, bytes]: ... +def dataframe_to_types( + df: pd.DataFrame, preserve_index: bool | None, columns: list[str] | None = None +) -> tuple[list[str], list[DataType], dict[bytes, bytes]]: ... +def dataframe_to_arrays( + df: pd.DataFrame, + schema: Schema, + preserve_index: bool | None, + nthreads: int = 1, + columns: list[str] | None = None, + safe: bool = True, +) -> tuple[Array, Schema, int]: ... +def get_datetimetz_type(values: _T, dtype: Any, type_: Any) -> tuple[_T, DataType]: ... +def make_datetimetz(unit: str, tz: str) -> DatetimeTZDtype: ... +def table_to_dataframe( + options: Any, + table: Table, + categories: Any = None, + ignore_metadata: bool = False, + types_mapper: Any = None, +) -> pd.DataFrame: ... +def get_pandas_logical_type_map() -> dict[str, str | type[np.generic]]: ... +def make_tz_aware(series: pd.Series, tz: str) -> pd.Series: ... diff --git a/python/pyarrow-stubs/substrait.pyi b/python/pyarrow-stubs/substrait.pyi new file mode 100644 index 000000000000..b78bbd8aebd7 --- /dev/null +++ b/python/pyarrow-stubs/substrait.pyi @@ -0,0 +1,38 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from pyarrow._substrait import ( + BoundExpressions, + SubstraitSchema, + deserialize_expressions, + deserialize_schema, + get_supported_functions, + run_query, + serialize_expressions, + serialize_schema, +) + +__all__ = [ + "BoundExpressions", + "get_supported_functions", + "run_query", + "deserialize_expressions", + "serialize_expressions", + "deserialize_schema", + "serialize_schema", + "SubstraitSchema", +] diff --git a/python/pyarrow-stubs/util.pyi b/python/pyarrow-stubs/util.pyi new file mode 100644 index 000000000000..fb933de1c011 --- /dev/null +++ b/python/pyarrow-stubs/util.pyi @@ -0,0 +1,56 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from collections.abc import Callable, Sequence +from os import PathLike +from typing import Any, Protocol, TypeVar + +_F = TypeVar("_F", bound=Callable[..., Any]) +_N = TypeVar("_N") + +class _DocStringComponents(Protocol): + _docstring_components: list[str] + +def doc( + *docstrings: str | _DocStringComponents | Callable[..., Any] | None, **params: Any +) -> Callable[[_F], _F]: ... +def _is_iterable(obj: Any) -> bool: ... +def _is_path_like(path: Any) -> bool: ... +def _stringify_path(path: str | PathLike[Any]) -> str: ... +def product(seq: Sequence[_N]) -> _N: ... +def get_contiguous_span( + shape: tuple[int, ...], strides: tuple[int, ...], itemsize: int +) -> tuple[int, int]: ... +def find_free_port() -> int: ... +def guid() -> str: ... +def _download_urllib(url: str, out_path: str | PathLike[Any]) -> None: ... +def _download_requests(url: str, out_path: str | PathLike[Any]) -> None: ... +def download_tzdata_on_windows() -> None: ... +def _deprecate_api( + old_name: str, + new_name: str, + api: Any, + next_version: str, + type: type[Warning] = ..., +) -> Any: ... +def _deprecate_class( + old_name: str, + new_class: type[Any], + next_version: str, + instancecheck: bool = True, +) -> type[Any]: ... +def _break_traceback_cycle_from_frame(frame: Any) -> None: ... diff --git a/python/pyproject.toml b/python/pyproject.toml index 36623967b013..79a150670673 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -120,15 +120,9 @@ files = ["pyarrow-stubs", "pyarrow-stubs-tests"] # usage is rejected, so an ignore that is no longer needed is an error there. warn_unused_ignores = true -# Modules that will be annotated in later PRs (GH-32609). Treat them as Any -# rather than type checking their sources. -[[tool.mypy.overrides]] -module = ["pyarrow.interchange.*"] -follow_imports = "skip" - # Optional dependencies without type hints. [[tool.mypy.overrides]] -module = ["fsspec", "sparse"] +module = ["cuda", "fsspec", "numba.*", "sparse"] ignore_missing_imports = true [tool.pyright] @@ -151,10 +145,10 @@ executionEnvironments = [ reportMissingModuleSource = false [tool.ty.analysis] -# Modules that will be annotated in later PRs (GH-32609), and the optional -# sparse dependency, which has no type hints. Treat them as Any. +# Optional dependencies without type hints. Treat them as Any. replace-imports-with-any = [ - "pyarrow.interchange.**", + "cuda", + "numba.**", "sparse", ] @@ -168,6 +162,7 @@ include = [ "pyarrow-stubs/__lib/array.pyi", "pyarrow-stubs/__lib/scalar.pyi", "pyarrow-stubs/_compute.pyi", + "pyarrow-stubs/_flight.pyi", "pyarrow-stubs/_hdfs.pyi", ] [tool.ty.overrides.rules] From c9cfca55c0c9bd41f69f2325887023e975dafb37 Mon Sep 17 00:00:00 2001 From: Rok Mihevc Date: Mon, 30 Nov 2026 18:36:28 +0100 Subject: [PATCH 33/33] GH-49199: [Python][Annotations] Finalize __init__.pyi, lib.pyi, and tests/util.pyi --- python/pyarrow-stubs/__init__.pyi | 21 ++++--- python/pyarrow-stubs/__lib/array.pyi | 8 +++ python/pyarrow-stubs/lib.pyi | 10 ++-- python/pyarrow-stubs/tests/util.pyi | 85 ++++++++++++++++++++++++++++ 4 files changed, 110 insertions(+), 14 deletions(-) create mode 100644 python/pyarrow-stubs/tests/util.pyi diff --git a/python/pyarrow-stubs/__init__.pyi b/python/pyarrow-stubs/__init__.pyi index 60b52f4a5a77..a3fc1549be38 100644 --- a/python/pyarrow-stubs/__init__.pyi +++ b/python/pyarrow-stubs/__init__.pyi @@ -15,11 +15,6 @@ # specific language governing permissions and limitations # under the License. -from typing import Any - -# The names that pyarrow/__init__.py imports from pyarrow.lib and that have -# stubs already. Type checkers only fall back to __getattr__ below for the -# names that aren't defined here. from pyarrow.lib import ( Array as Array, ArrowCancelled as ArrowCancelled, @@ -205,6 +200,7 @@ from pyarrow.lib import ( UuidType as UuidType, VersionInfo as VersionInfo, allocate_buffer as allocate_buffer, + arange as arange, array as array, binary as binary, binary_view as binary_view, @@ -219,6 +215,7 @@ from pyarrow.lib import ( cpp_build_info as cpp_build_info, cpp_version as cpp_version, cpp_version_info as cpp_version_info, + cpu_count as cpu_count, create_memory_map as create_memory_map, date32 as date32, date64 as date64, @@ -247,6 +244,7 @@ from pyarrow.lib import ( int64 as int64, int8 as int8, io_thread_count as io_thread_count, + is_opentelemetry_enabled as is_opentelemetry_enabled, jemalloc_memory_pool as jemalloc_memory_pool, jemalloc_set_decay_ms as jemalloc_set_decay_ms, json_ as json_, @@ -276,6 +274,7 @@ from pyarrow.lib import ( runtime_info as runtime_info, scalar as scalar, schema as schema, + set_cpu_count as set_cpu_count, set_io_thread_count as set_io_thread_count, set_memory_pool as set_memory_pool, set_timezone_db_path as set_timezone_db_path, @@ -319,8 +318,12 @@ from pyarrow.ipc import ( # pyarrow/__init__.py imports pyarrow.lib._NULL as NULL NULL: NullScalar +__version__: str | None -# TODO(GH-48970): remove __getattr__ before release as this -# will annotate non-existing attributes as Any. -# https://github.com/apache/arrow/issues/48970 -def __getattr__(name: str) -> Any: ... +def show_versions() -> None: ... +def show_info() -> None: ... +def have_libhdfs() -> bool: ... +def get_include() -> str: ... +def get_libraries() -> list[str]: ... +def create_library_symlinks() -> None: ... +def get_library_dirs() -> list[str]: ... diff --git a/python/pyarrow-stubs/__lib/array.pyi b/python/pyarrow-stubs/__lib/array.pyi index 55a2699f4f6b..83f4f9677028 100644 --- a/python/pyarrow-stubs/__lib/array.pyi +++ b/python/pyarrow-stubs/__lib/array.pyi @@ -89,6 +89,13 @@ def asarray( values: _ArrayConstructorInput, type: Any | None = None, ) -> Array: ... +def arange( + start: int, + stop: int, + step: int = 1, + *, + memory_pool: MemoryPool | None = None, +) -> Int64Array: ... def nulls( size: int, type: Any | None = None, @@ -622,6 +629,7 @@ def concat_arrays( def _empty_array(type: DataType) -> Array: ... __all__ = [ + "arange", "array", "asarray", "nulls", diff --git a/python/pyarrow-stubs/lib.pyi b/python/pyarrow-stubs/lib.pyi index 2aac2518ba71..e0a41c8f5d81 100644 --- a/python/pyarrow-stubs/lib.pyi +++ b/python/pyarrow-stubs/lib.pyi @@ -15,11 +15,9 @@ # specific language governing permissions and limitations # under the License. -# Stub for the pyarrow.lib C extension module. Re-exports the modules that -# have been annotated so far; everything else falls back to Any via -# __getattr__ until it gets annotated in subsequent PRs. +# Stub for the pyarrow.lib C extension module. -from typing import Any, Self, final +from typing import Self, final from pyarrow.__lib.array import * # noqa: F401,F403 from pyarrow.__lib.builder import * # noqa: F401,F403 @@ -44,4 +42,6 @@ class MonthDayNano(tuple[int, int, int]): def __new__(cls, sequence: tuple[int, int, int] | list[int]) -> Self: ... -def __getattr__(name: str) -> Any: ... +def cpu_count() -> int: ... +def set_cpu_count(count: int) -> None: ... +def is_opentelemetry_enabled() -> bool: ... diff --git a/python/pyarrow-stubs/tests/util.pyi b/python/pyarrow-stubs/tests/util.pyi new file mode 100644 index 000000000000..91535fce5f47 --- /dev/null +++ b/python/pyarrow-stubs/tests/util.pyi @@ -0,0 +1,85 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +from collections.abc import Callable +from contextlib import AbstractContextManager +from decimal import Decimal +from os import PathLike +from typing import Any, ClassVar, Literal +import socket + +import pyarrow.fs + +def randsign() -> int: ... +def random_seed(seed: int) -> AbstractContextManager[None]: ... +def randdecimal(precision: int, scale: int) -> Decimal: ... +def random_ascii(length: int) -> bytes: ... +def rands(nchars: int) -> str: ... +def get_modified_env_with_pythonpath() -> dict[str, str]: ... +def invoke_script(script_name: str, *args: str) -> None: ... +def changed_environ(name: str, value: str) -> AbstractContextManager[None]: ... +def change_cwd(path: str | PathLike[str]) -> AbstractContextManager[None]: ... +def disabled_gc() -> AbstractContextManager[None]: ... +def _filesystem_uri(path: str) -> str: ... +def memory_leak_check( + f: Callable[[], Any], + metric: Literal["rss", "vms", "shared"] = "rss", + threshold: int = 131072, + iterations: int = 10, + check_interval: int = 1, +) -> None: ... + +class FSProtocolClass: + def __init__(self, path: str | PathLike[str]) -> None: ... + def __fspath__(self) -> str: ... + +class ProxyHandler(pyarrow.fs.FileSystemHandler): + __hash__: ClassVar[None] # type: ignore[assignment] + _fs: pyarrow.fs.FileSystem + def __init__(self, fs: pyarrow.fs.FileSystem) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def get_type_name(self) -> str: ... + def normalize_path(self, path: str) -> str: ... + def get_file_info(self, paths: str | list[str]) -> list[pyarrow.fs.FileInfo]: ... + def get_file_info_selector( + self, selector: pyarrow.fs.FileSelector + ) -> list[pyarrow.fs.FileInfo]: ... + def create_dir(self, path: str, recursive: bool) -> None: ... + def delete_dir(self, path: str) -> None: ... + def delete_dir_contents(self, path: str, missing_dir_ok: bool) -> None: ... + def delete_root_dir_contents(self) -> None: ... + def delete_file(self, path: str) -> None: ... + def move(self, src: str, dest: str) -> None: ... + def copy_file(self, src: str, dest: str) -> None: ... + def open_input_stream(self, path: str) -> Any: ... + def open_input_file(self, path: str) -> Any: ... + def open_output_stream(self, path: str, metadata: dict[str, str]) -> Any: ... + def open_append_stream(self, path: str, metadata: dict[str, str]) -> Any: ... + +def _ensure_minio_component_version(component: str, minimum_year: int) -> bool: ... +def _run_mc_command(mcdir: str, *args: str) -> None: ... +def windows_has_tzdata() -> bool: ... +def running_on_musllinux() -> bool: ... +def signal_wakeup_fd( + *, warn_on_full_buffer: bool = False +) -> AbstractContextManager[socket.socket]: ... +def _configure_s3_limited_user( + s3_server: dict[str, Any], policy: str, username: str, password: str +) -> None: ... +def _wait_for_minio_startup( + mcdir: str, address: str, access_key: str, secret_key: str +) -> None: ...