From f3910c25ee55ad0b2dad8c70a6d32abc1207d910 Mon Sep 17 00:00:00 2001 From: Tadeja Kadunc Date: Thu, 26 Nov 2026 17:55:19 +0100 Subject: [PATCH 1/3] Improved MetadataMapping --- python/pyarrow-stubs-tests/test_table.py | 20 ++++++++++++++ python/pyarrow-stubs-tests/test_types.py | 7 +++++ python/pyarrow-stubs/__lib/table.pyi | 33 +++++++----------------- python/pyarrow-stubs/__lib/types.pyi | 14 +++++----- python/pyarrow-stubs/_stubs_typing.pyi | 10 ++++++- 5 files changed, 51 insertions(+), 33 deletions(-) diff --git a/python/pyarrow-stubs-tests/test_table.py b/python/pyarrow-stubs-tests/test_table.py index 8bc93a2bd05..38b2ea28b5e 100644 --- a/python/pyarrow-stubs-tests/test_table.py +++ b/python/pyarrow-stubs-tests/test_table.py @@ -179,6 +179,26 @@ def test_record_batch() -> None: pa.RecordBatch) +def test_metadata_mappings() -> None: + # Mappings with only str or only bytes keys are accepted, not just + # Mapping[str | bytes, ...] (Mapping is invariant in its key type). + str_meta: dict[str, str] = {"k": "v"} + bytes_meta: dict[bytes, bytes] = {b"k": b"v"} + expected = {b"k": b"v"} + + table = pa.table({"a": [1]}, metadata=str_meta) + batch = pa.record_batch({"a": [1]}, metadata=bytes_meta) + assert table.schema.metadata == batch.schema.metadata == expected + from_dict = pa.Table.from_pydict({"a": [1]}, metadata=str_meta) + from_rows = pa.RecordBatch.from_pylist([{"a": 1}], metadata=bytes_meta) + assert from_dict.schema.metadata == from_rows.schema.metadata == expected + + replacement = MappingProxyType({"k": "updated"}) + table = table.replace_schema_metadata(replacement) + batch = batch.replace_schema_metadata(replacement) + assert table.schema.metadata == batch.schema.metadata == {b"k": b"updated"} + + def test_record_batch_from_pandas() -> None: pd = pytest.importorskip("pandas") df = pd.DataFrame({"a": [1], "b": [2]}) diff --git a/python/pyarrow-stubs-tests/test_types.py b/python/pyarrow-stubs-tests/test_types.py index ebbed90353d..f18204e29fd 100644 --- a/python/pyarrow-stubs-tests/test_types.py +++ b/python/pyarrow-stubs-tests/test_types.py @@ -136,6 +136,13 @@ def test_schema() -> None: check(assert_type(schema.field("a"), pa.Field), pa.Field) check(assert_type(schema[0], pa.Field), pa.Field) + # Mappings with only str or only bytes keys are accepted. + str_fields: dict[str, pa.DataType] = {"a": pa.int32()} + bytes_fields: dict[bytes, pa.DataType] = {b"a": pa.int32()} + for fields in (str_fields, bytes_fields): + assert pa.schema(fields).names == ["a"] + assert pa.struct(fields).field(0).name == "a" + def test_key_value_metadata() -> None: # The runtime yields generators instead of Mapping views (duplicated keys) diff --git a/python/pyarrow-stubs/__lib/table.pyi b/python/pyarrow-stubs/__lib/table.pyi index ac697568d73..87a95618353 100644 --- a/python/pyarrow-stubs/__lib/table.pyi +++ b/python/pyarrow-stubs/__lib/table.pyi @@ -39,6 +39,7 @@ from pyarrow._stubs_typing import ( Indices, MapsAsPydicts, Mask, + MetadataMapping, NullEncoding, NullPlacement, NullSelectionBehavior, @@ -277,14 +278,14 @@ class _Tabular(_PandasConvertible): | SupportsArrowDeviceArray, ], schema: Schema | None = None, - metadata: Mapping[str | bytes, str | bytes] | None = None, + metadata: MetadataMapping | None = None, ) -> Self: ... @classmethod def from_pylist( cls, mapping: Sequence[Mapping[str, Any]], schema: Schema | None = None, - metadata: Mapping[str | bytes, str | bytes] | None = None, + metadata: MetadataMapping | None = None, ) -> Self: ... def itercolumns(self) -> Iterator[_ArrayOrChunkedArray]: ... @property @@ -331,11 +332,7 @@ class RecordBatch(_Tabular): def validate(self, *, full: bool = False) -> None: ... def replace_schema_metadata( self, - metadata: dict[str, str] - | dict[bytes, bytes] - | dict[bytes, str] - | dict[str, bytes] - | None = None, + metadata: MetadataMapping | None = None, ) -> RecordBatch: ... @property def num_columns(self) -> int: ... @@ -375,11 +372,7 @@ class RecordBatch(_Tabular): arrays: list[Any], names: Sequence[str] | None = None, schema: Schema | None = None, - metadata: Mapping[bytes, bytes] - | Mapping[str, str] - | Mapping[bytes, str] - | Mapping[str, bytes] - | None = None, + metadata: MetadataMapping | None = None, ) -> RecordBatch: ... @classmethod def from_pandas( @@ -445,11 +438,7 @@ class Table(_Tabular): def select(self, columns: Iterable[str | int]) -> Table: ... def replace_schema_metadata( self, - metadata: dict[str, str] - | dict[bytes, bytes] - | dict[bytes, str] - | dict[str, bytes] - | None = None, + metadata: MetadataMapping | None = None, ) -> Table: ... def flatten(self, memory_pool: MemoryPool | None = None) -> Table: ... def combine_chunks(self, memory_pool: MemoryPool | None = None) -> Table: ... @@ -485,11 +474,7 @@ class Table(_Tabular): | NDArray[Any], names: Sequence[str] | None = None, schema: Schema | None = None, - metadata: Mapping[bytes, bytes] - | Mapping[str, str] - | Mapping[bytes, str] - | Mapping[str, bytes] - | None = None, + metadata: MetadataMapping | None = None, ) -> Table: ... @staticmethod def from_struct_array(struct_array: StructArray | ChunkedArray) -> Table: ... @@ -574,7 +559,7 @@ def record_batch( | SupportsArrowDeviceArray, names: list[str] | Schema | None = None, schema: Schema | None = None, - metadata: Mapping[str | bytes, str | bytes] | None = None, + metadata: MetadataMapping | None = None, ) -> RecordBatch: ... def table( data: dict[str, Any] @@ -586,7 +571,7 @@ def table( | SupportsArrowDeviceArray, names: list[str] | Schema | None = None, schema: Schema | None = None, - metadata: Mapping[str | bytes, str | bytes] | None = None, + metadata: MetadataMapping | None = None, nthreads: int | None = None, ) -> Table: ... def concat_tables( diff --git a/python/pyarrow-stubs/__lib/types.pyi b/python/pyarrow-stubs/__lib/types.pyi index fe4dc10abc2..4d71dcbed6c 100644 --- a/python/pyarrow-stubs/__lib/types.pyi +++ b/python/pyarrow-stubs/__lib/types.pyi @@ -38,6 +38,7 @@ from pyarrow._stubs_typing import ( IntegerType, LargeBinaryType, LargeStringType, + MetadataMapping, MonthDayNanoIntervalType, NullType, StringType, @@ -281,14 +282,8 @@ def unregister_extension_type(type_name: str) -> None: ... _FieldName: TypeAlias = str | bytes _StrOrBytes: TypeAlias = str | bytes -_MetadataMapping: TypeAlias = ( - Mapping[bytes, bytes] - | Mapping[str, str] - | Mapping[bytes, str] - | Mapping[str, bytes] -) _MetadataIterable: TypeAlias = Iterable[tuple[_StrOrBytes, _StrOrBytes]] -_KeyValueMetadataInput: TypeAlias = _MetadataMapping | _MetadataIterable +_KeyValueMetadataInput: TypeAlias = MetadataMapping | _MetadataIterable _DataTypeAlias: TypeAlias = Literal[ "null", "bool", @@ -407,7 +402,10 @@ _FieldTuple: TypeAlias = ( ] ) _StructFieldsInput: TypeAlias = ( - Iterable[Field | _FieldTuple] | Mapping[_FieldName, _DataTypeLike] + Iterable[Field | _FieldTuple] + | Mapping[str, _DataTypeLike] + | Mapping[bytes, _DataTypeLike] + | Mapping[_FieldName, _DataTypeLike] ) _SchemaFieldsInput: TypeAlias = _StructFieldsInput diff --git a/python/pyarrow-stubs/_stubs_typing.pyi b/python/pyarrow-stubs/_stubs_typing.pyi index 17ee2cffc31..80dcd7ea07d 100644 --- a/python/pyarrow-stubs/_stubs_typing.pyi +++ b/python/pyarrow-stubs/_stubs_typing.pyi @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -from collections.abc import Sequence +from collections.abc import Mapping, Sequence from typing import Any, Literal, Protocol, TypeAlias import numpy as np @@ -36,6 +36,14 @@ Indices: TypeAlias = ( Sequence[int | None] | NDArray[np.integer[Any]] | Array | ChunkedArray ) +# Key-value metadata. Mapping is invariant in its key type, so mappings with +# only str or only bytes keys are listed next to the mixed one. +MetadataMapping: TypeAlias = ( + Mapping[str, str | bytes] + | Mapping[bytes, str | bytes] + | Mapping[str | bytes, str | bytes] +) + class SupportsArrowStream(Protocol): def __arrow_c_stream__(self, requested_schema: Any = None, /) -> Any: ... From b42b942f40c93977d0fda3bbbd3276a22e67b0c4 Mon Sep 17 00:00:00 2001 From: Tadeja Kadunc Date: Thu, 26 Nov 2026 18:45:06 +0100 Subject: [PATCH 2/3] Improved Array.take/filter/fill_null() --- python/pyarrow-stubs-tests/test_array.py | 11 ++++++++- python/pyarrow-stubs/__lib/array.pyi | 29 +++++++++++++++++++++--- python/pyarrow-stubs/_stubs_typing.pyi | 8 +++---- 3 files changed, 40 insertions(+), 8 deletions(-) diff --git a/python/pyarrow-stubs-tests/test_array.py b/python/pyarrow-stubs-tests/test_array.py index ab57edd3491..0e60e1986a9 100644 --- a/python/pyarrow-stubs-tests/test_array.py +++ b/python/pyarrow-stubs-tests/test_array.py @@ -77,6 +77,15 @@ def test_array() -> None: bool_mask = cast(pa.BooleanArray, pa.array([True, False, True])) check(assert_type(arr.filter(bool_mask), pa.Int64Array), pa.Int64Array) + chunked = pa.chunked_array([[0, 1, 2]]) + mask = pa.chunked_array([[True, False, True]]) + check(assert_type(arr.take(chunked), pa.ChunkedArray), pa.ChunkedArray) + check(assert_type(arr.filter(mask), pa.ChunkedArray), pa.ChunkedArray) + check(assert_type(arr.fill_null(chunked), pa.ChunkedArray), pa.ChunkedArray) + if TYPE_CHECKING: + fill = cast(int | pa.ChunkedArray, chunked) + assert_type(arr.fill_null(fill), pa.Int64Array | pa.ChunkedArray) + def test_array_constructors() -> None: check(assert_type(pa.array([1, 2]), pa.Array), pa.Int64Array) @@ -296,7 +305,7 @@ def test_invalid_usage() -> None: # Arrays define __eq__ but not __hash__, hence unhashable at runtime _: Hashable = arr # type: ignore[assignment] # ty: ignore[invalid-assignment] arr.sort(null_placement="first") # type: ignore[arg-type] - arr.filter([True], null_selection_behavior="keep") # type: ignore[arg-type] + arr.filter([True], null_selection_behavior="keep") # type: ignore[call-overload] # ty: ignore[no-matching-overload] # noqa: E501 arr.dictionary_encode("drop") # type: ignore[arg-type] arr.to_pylist(maps_as_pydicts="loose") # type: ignore[arg-type] # Generators aren't accepted, only Sequences diff --git a/python/pyarrow-stubs/__lib/array.pyi b/python/pyarrow-stubs/__lib/array.pyi index f85e4e3beb7..ca0b333f110 100644 --- a/python/pyarrow-stubs/__lib/array.pyi +++ b/python/pyarrow-stubs/__lib/array.pyi @@ -17,6 +17,8 @@ import builtins from collections.abc import Collection, Iterable, Iterator, Sequence +from datetime import date +from decimal import Decimal from typing import Any, ClassVar, Self, SupportsIndex, TypeAlias, overload import numpy as np @@ -31,6 +33,8 @@ from pyarrow._stubs_typing import ( Indices, MapsAsPydicts, Mask, + NonChunkedIndices, + NonChunkedMask, NullEncoding, NullPlacement, NullSelectionBehavior, @@ -196,17 +200,36 @@ class Array(_PandasConvertible): def is_null(self, *, nan_is_null: bool = False) -> BooleanArray: ... def is_nan(self) -> BooleanArray: ... def is_valid(self) -> BooleanArray: ... - def fill_null(self, fill_value: Any) -> Self: ... + @overload + def fill_null(self, fill_value: ChunkedArray) -> ChunkedArray: ... + @overload + def fill_null( + self, + fill_value: Array | float | str | bytes | date | Decimal | np.generic | None, + ) -> Self: ... + @overload + def fill_null(self, fill_value: object) -> Self | ChunkedArray: ... @overload def __getitem__(self, key: SupportsIndex) -> Scalar: ... @overload def __getitem__(self, key: builtins.slice) -> Self: ... def slice(self, offset: int = 0, length: int | None = None) -> Self: ... - def take(self, indices: Indices) -> Self: ... + @overload + def take(self, indices: ChunkedArray) -> ChunkedArray: ... + @overload + def take(self, indices: NonChunkedIndices) -> Self: ... def drop_null(self) -> Self: ... + @overload + def filter( + self, + mask: ChunkedArray, + *, + null_selection_behavior: NullSelectionBehavior = "drop", + ) -> ChunkedArray: ... + @overload def filter( self, - mask: Mask, + mask: NonChunkedMask, *, null_selection_behavior: NullSelectionBehavior = "drop", ) -> Self: ... diff --git a/python/pyarrow-stubs/_stubs_typing.pyi b/python/pyarrow-stubs/_stubs_typing.pyi index 80dcd7ea07d..888126ed9df 100644 --- a/python/pyarrow-stubs/_stubs_typing.pyi +++ b/python/pyarrow-stubs/_stubs_typing.pyi @@ -31,10 +31,10 @@ NullPlacement: TypeAlias = Literal["at_start", "at_end"] NullSelectionBehavior: TypeAlias = Literal["drop", "emit_null"] TimeUnit: TypeAlias = Literal["s", "ms", "us", "ns"] -Mask: TypeAlias = Sequence[bool | None] | NDArray[np.bool_] | Array | ChunkedArray -Indices: TypeAlias = ( - Sequence[int | None] | NDArray[np.integer[Any]] | Array | ChunkedArray -) +NonChunkedMask: TypeAlias = Sequence[bool | None] | NDArray[np.bool_] | Array +Mask: TypeAlias = NonChunkedMask | ChunkedArray +NonChunkedIndices: TypeAlias = Sequence[int | None] | NDArray[np.integer[Any]] | Array +Indices: TypeAlias = NonChunkedIndices | ChunkedArray # Key-value metadata. Mapping is invariant in its key type, so mappings with # only str or only bytes keys are listed next to the mixed one. From 9fc8fac41766d8627940f4279ae579ee178b88aa Mon Sep 17 00:00:00 2001 From: Tadeja Kadunc Date: Thu, 26 Nov 2026 19:16:30 +0100 Subject: [PATCH 3/3] Improved RecordBatch.take() --- python/pyarrow-stubs-tests/test_table.py | 9 ++++++++- python/pyarrow-stubs/__lib/table.pyi | 4 +++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/python/pyarrow-stubs-tests/test_table.py b/python/pyarrow-stubs-tests/test_table.py index 38b2ea28b5e..b19b1e44dee 100644 --- a/python/pyarrow-stubs-tests/test_table.py +++ b/python/pyarrow-stubs-tests/test_table.py @@ -153,7 +153,14 @@ def test_record_batch() -> None: check(assert_type(batch.column(0), pa.Array | pa.ChunkedArray), pa.Array) check(assert_type(batch.slice(1), pa.RecordBatch), pa.RecordBatch) - check(assert_type(pa.Table.from_batches([batch]), pa.Table), pa.Table) + table = check(assert_type(pa.Table.from_batches([batch]), pa.Table), pa.Table) + indices = pa.chunked_array([[1, 0]]) + check(assert_type(batch.take(indices.chunk(0)), pa.RecordBatch), + pa.RecordBatch) + check(assert_type(table.take(indices), pa.Table), pa.Table) + with pytest.raises(pa.ArrowNotImplementedError): + batch.take(indices) # type: ignore[arg-type] + check(assert_type(pa.concat_batches([batch, batch]), pa.RecordBatch), pa.RecordBatch) check(assert_type(batch.add_column(0, "b", pa.array([3, 4])), diff --git a/python/pyarrow-stubs/__lib/table.pyi b/python/pyarrow-stubs/__lib/table.pyi index 87a95618353..7ff84567b78 100644 --- a/python/pyarrow-stubs/__lib/table.pyi +++ b/python/pyarrow-stubs/__lib/table.pyi @@ -40,6 +40,7 @@ from pyarrow._stubs_typing import ( MapsAsPydicts, Mask, MetadataMapping, + NonChunkedIndices, NullEncoding, NullPlacement, NullSelectionBehavior, @@ -301,7 +302,7 @@ class _Tabular(_PandasConvertible): sorting: str | Sequence[tuple[str, Order] | tuple[str, Order, NullPlacement]], **kwargs: Any, ) -> Self: ... - def take(self, indices: Indices) -> Self: ... + def take(self, indices: NonChunkedIndices) -> Self: ... def filter( self, mask: Mask | Expression, @@ -433,6 +434,7 @@ _JoinType: TypeAlias = Literal[ ] class Table(_Tabular): + def take(self, indices: Indices) -> Self: ... def validate(self, *, full: bool = False) -> None: ... def slice(self, offset: int = 0, length: int | None = None) -> Table: ... def select(self, columns: Iterable[str | int]) -> Table: ...