Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion python/pyarrow-stubs-tests/test_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
29 changes: 28 additions & 1 deletion python/pyarrow-stubs-tests/test_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])),
Expand All @@ -179,6 +186,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]})
Expand Down
7 changes: 7 additions & 0 deletions python/pyarrow-stubs-tests/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
29 changes: 26 additions & 3 deletions python/pyarrow-stubs/__lib/array.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -31,6 +33,8 @@ from pyarrow._stubs_typing import (
Indices,
MapsAsPydicts,
Mask,
NonChunkedIndices,
NonChunkedMask,
NullEncoding,
NullPlacement,
NullSelectionBehavior,
Expand Down Expand Up @@ -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: ...
Expand Down
37 changes: 12 additions & 25 deletions python/pyarrow-stubs/__lib/table.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ from pyarrow._stubs_typing import (
Indices,
MapsAsPydicts,
Mask,
MetadataMapping,
NonChunkedIndices,
NullEncoding,
NullPlacement,
NullSelectionBehavior,
Expand Down Expand Up @@ -277,14 +279,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
Expand All @@ -300,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,
Expand Down Expand Up @@ -331,11 +333,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: ...
Expand Down Expand Up @@ -375,11 +373,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(
Expand Down Expand Up @@ -440,16 +434,13 @@ _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: ...
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: ...
Expand Down Expand Up @@ -485,11 +476,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: ...
Expand Down Expand Up @@ -574,7 +561,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]
Expand All @@ -586,7 +573,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(
Expand Down
14 changes: 6 additions & 8 deletions python/pyarrow-stubs/__lib/types.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ from pyarrow._stubs_typing import (
IntegerType,
LargeBinaryType,
LargeStringType,
MetadataMapping,
MonthDayNanoIntervalType,
NullType,
StringType,
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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

Expand Down
16 changes: 12 additions & 4 deletions python/pyarrow-stubs/_stubs_typing.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -31,9 +31,17 @@ 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.
MetadataMapping: TypeAlias = (
Mapping[str, str | bytes]
| Mapping[bytes, str | bytes]
| Mapping[str | bytes, str | bytes]
)

class SupportsArrowStream(Protocol):
Expand Down
Loading