From 3dbb498a3a7b7ed6538ebab460b5ae01834ccd57 Mon Sep 17 00:00:00 2001 From: Rok Mihevc Date: Fri, 13 Nov 2026 14:06:32 +0100 Subject: [PATCH 01/35] 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 | 9 +- 10 files changed, 2538 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 90a79999511e..86a85448e2c3 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..a035c65a2789 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,11 @@ 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. Expression.__eq__ and __ne__ return an Expression rather than a bool. incompatible-method-override = "ignore" [[tool.ty.overrides]] From 79fc64494b7ff7fb4393ac043bb131b182fd9215 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Tue, 17 Nov 2026 06:19:33 +0100 Subject: [PATCH 02/35] 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 9884c5c2091c2f77133063cea8e26098e20cc86b Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Tue, 17 Nov 2026 14:58:13 +0100 Subject: [PATCH 03/35] 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 93441bd519cc09e5e2180cf52b626a01aee26839 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Wed, 18 Nov 2026 15:52:15 +0100 Subject: [PATCH 04/35] 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 aa7a55180f4c846677abd02b58e993e1ea863300 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Thu, 19 Nov 2026 10:15:43 +0100 Subject: [PATCH 05/35] 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 3bf05303cada514d51b059ac4f5cfc0ef8742f01 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Thu, 19 Nov 2026 10:30:41 +0100 Subject: [PATCH 06/35] 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 b70f4e5c28da0b374bd09b43e62894530cfdb37f Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Thu, 19 Nov 2026 11:02:11 +0100 Subject: [PATCH 07/35] 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 c70bbdb45028e4b129eb0cd5f4c1929fa843943b Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Thu, 19 Nov 2026 17:00:04 +0100 Subject: [PATCH 08/35] 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 a530395af4f16ba3040aec1d6c4906c86e11bdd4 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Fri, 20 Nov 2026 06:37:53 +0100 Subject: [PATCH 09/35] 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 1437722363cf2a224c5c1e573c26b3dcfa666153 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Fri, 20 Nov 2026 09:12:15 +0100 Subject: [PATCH 10/35] 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 765a1bcc40bf3c8d7450f4b72c488f70eb7a8367 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Fri, 20 Nov 2026 11:51:31 +0100 Subject: [PATCH 11/35] 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 b40ed259081a4287e7c2ace5dc92f767466fbf79 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Fri, 20 Nov 2026 12:31:59 +0100 Subject: [PATCH 12/35] 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 43947417499d3a2d847870cb0c7005adefc24ba0 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Sat, 21 Nov 2026 12:40:26 +0100 Subject: [PATCH 13/35] 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 86a85448e2c3..90a79999511e 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 1b56756020436c0cf5712f9043ef1d6ac503873c Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Mon, 23 Nov 2026 07:52:27 +0100 Subject: [PATCH 14/35] 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 eca0aa95c9e27fe296f3d1175dafbf87c7ad749b Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Mon, 23 Nov 2026 08:30:22 +0100 Subject: [PATCH 15/35] 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 96a8f4cfbdc0d98e33c5292153925fcf6df7982a Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Mon, 23 Nov 2026 10:45:21 +0100 Subject: [PATCH 16/35] 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 f9eefdba09061918336501ae85a26ee3a4bb2978 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Mon, 23 Nov 2026 11:28:36 +0100 Subject: [PATCH 17/35] 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 8a4eac44ad84bebfc868d69618efde8b276c036a Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Tue, 24 Nov 2026 11:19:50 +0100 Subject: [PATCH 18/35] 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 a77423f336b2b70db0f308cadaf0ba1937830b08 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Wed, 25 Nov 2026 06:14:41 +0100 Subject: [PATCH 19/35] 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 7a4ebfbed8494687f69ef759d81f5f8ac72458d3 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Wed, 25 Nov 2026 06:26:35 +0100 Subject: [PATCH 20/35] 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 12b14402dc125f73294b1f7467f71995a9944028 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Wed, 25 Nov 2026 07:55:31 +0100 Subject: [PATCH 21/35] 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 f4c18d58407a08bc0840665f99c30c17c8a6db92 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Fri, 27 Nov 2026 06:28:17 +0100 Subject: [PATCH 22/35] 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 0a7f2ce6e055e96c1e650b1777f138688545c717 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Fri, 27 Nov 2026 06:41:14 +0100 Subject: [PATCH 23/35] 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 e5001d181c5e3e8b368f37f7f809ef72c1073558 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Fri, 27 Nov 2026 07:58:19 +0100 Subject: [PATCH 24/35] 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 ff99bed4fb98bebd7978ff2f4cb72287ee604f87 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Fri, 27 Nov 2026 08:06:16 +0100 Subject: [PATCH 25/35] 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 dea6869acca4fa5b54e8c6be450c22d2e249f51c Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Fri, 27 Nov 2026 08:29:22 +0100 Subject: [PATCH 26/35] 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 d4813f9c53960d66187568987056f90a25925afc Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Fri, 27 Nov 2026 08:39:58 +0100 Subject: [PATCH 27/35] 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 38fb88a97addc828c241d84980ca905148ed752c Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Wed, 2 Dec 2026 10:02:04 +0100 Subject: [PATCH 28/35] Remove scalar placeholders in compute.pyi --- python/pyarrow-stubs/compute.pyi | 81 +++++++++++++++----------------- 1 file changed, 38 insertions(+), 43 deletions(-) diff --git a/python/pyarrow-stubs/compute.pyi b/python/pyarrow-stubs/compute.pyi index dc0f690e874f..4da43929519b 100644 --- a/python/pyarrow-stubs/compute.pyi +++ b/python/pyarrow-stubs/compute.pyi @@ -24,47 +24,6 @@ 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 -# 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, - Scalar, - StringScalar, - StringViewScalar, - StructScalar, - Time32Scalar, - Time64Scalar, - TimestampScalar, - UInt8Scalar, - UInt16Scalar, - UInt32Scalar, - UInt64Scalar, -) from pyarrow._compute import ( ArraySortOptions as ArraySortOptions, AssumeTimezoneOptions as AssumeTimezoneOptions, @@ -174,40 +133,77 @@ from pyarrow.lib import ( Array, BaseListArray, BinaryArray, + BinaryScalar, BinaryViewArray, + BinaryViewScalar, BooleanArray, + BooleanScalar, ChunkedArray, DataType, Date32Array, + Date32Scalar, Date64Array, + Date64Scalar, Decimal32Array, + Decimal32Scalar, Decimal64Array, + Decimal64Scalar, Decimal128Array, + Decimal128Scalar, Decimal256Array, + Decimal256Scalar, DictionaryArray, DoubleArray, + DoubleScalar, DurationArray, + DurationScalar, FixedSizeBinaryArray, + FixedSizeBinaryScalar, + FixedSizeListScalar, FloatingPointArray, + FloatScalar, + HalfFloatScalar, + Int8Scalar, + Int16Scalar, Int32Array, + Int32Scalar, Int64Array, + Int64Scalar, IntegerArray, KeyValueMetadata, LargeBinaryArray, + LargeBinaryScalar, + LargeListScalar, + LargeListViewScalar, LargeStringArray, + LargeStringScalar, + ListScalar, + ListViewScalar, MemoryPool, MonthDayNanoIntervalArray, + MonthDayNanoIntervalScalar, NumericArray, RecordBatch, RunEndEncodedArray, + Scalar, StringArray, + StringScalar, StringViewArray, + StringViewScalar, StructArray, + StructScalar, Table, Time32Array, + Time32Scalar, Time64Array, + Time64Scalar, TimestampArray, + TimestampScalar, + UInt8Scalar, + UInt16Scalar, + UInt32Scalar, UInt64Array, + UInt64Scalar, ) _P = ParamSpec("_P") @@ -219,8 +215,7 @@ 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. +# The inputs and outputs of the compute functions, by kind of data. _SignedIntegerScalar: TypeAlias = Int8Scalar | Int16Scalar | Int32Scalar | Int64Scalar _UnsignedIntegerScalar: TypeAlias = ( UInt8Scalar | UInt16Scalar | UInt32Scalar | UInt64Scalar From 30064ca632c6cc749f307ae804a02d28e919f1af Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Wed, 2 Dec 2026 10:17:07 +0100 Subject: [PATCH 29/35] Define shared NumericLiteral and TemporalLiteral --- python/pyarrow-stubs-tests/test_scalar.py | 4 + python/pyarrow-stubs/__lib/scalar.pyi | 18 ++-- python/pyarrow-stubs/_stubs_typing.pyi | 7 ++ python/pyarrow-stubs/compute.pyi | 104 +++++++++++----------- 4 files changed, 74 insertions(+), 59 deletions(-) diff --git a/python/pyarrow-stubs-tests/test_scalar.py b/python/pyarrow-stubs-tests/test_scalar.py index e27a2229680f..4f2651e622b9 100644 --- a/python/pyarrow-stubs-tests/test_scalar.py +++ b/python/pyarrow-stubs-tests/test_scalar.py @@ -81,6 +81,10 @@ def test_scalar_operators() -> None: check(assert_type(s ^ 3, pa.Scalar), pa.Int64Scalar) check(assert_type(s << 1, pa.Scalar), pa.Int64Scalar) check(assert_type(s >> 1, pa.Scalar), pa.Int64Scalar) + # Other Python values are converted to scalars too + check(assert_type(s + Decimal("1.5"), pa.Scalar), pa.Decimal128Scalar) + date = pa.scalar(dt.date(2020, 1, 1)) + check(assert_type(date + dt.timedelta(days=1), pa.Scalar), pa.TimestampScalar) if TYPE_CHECKING: # Scalars don't implement the reflected operators diff --git a/python/pyarrow-stubs/__lib/scalar.pyi b/python/pyarrow-stubs/__lib/scalar.pyi index f206434db263..50804b0ecebc 100644 --- a/python/pyarrow-stubs/__lib/scalar.pyi +++ b/python/pyarrow-stubs/__lib/scalar.pyi @@ -23,7 +23,7 @@ from uuid import UUID from numpy.typing import NDArray from pyarrow._compute import CastOptions -from pyarrow._stubs_typing import MapsAsPydicts +from pyarrow._stubs_typing import MapsAsPydicts, NumericLiteral, TemporalLiteral from pyarrow.lib import ( Array, BaseExtensionType, @@ -57,14 +57,17 @@ class Scalar(_Weakrefable): def __abs__(self) -> Scalar: ... def __neg__(self) -> Scalar: ... # The binary operators call the compute functions. An Array or ChunkedArray - # operand gives one of the same kind, a Scalar or a number gives a Scalar. - # Other operands (e.g. a list or a date) may give either. + # operand gives one of the same kind, a Scalar or a Python value such as a + # number or a date gives a Scalar. Other operands (e.g. a list) may give + # either. @overload def __add__(self, other: ChunkedArray, /) -> ChunkedArray: ... @overload def __add__(self, other: Array, /) -> Array: ... @overload - def __add__(self, other: Scalar | float, /) -> Scalar: ... + def __add__( + self, other: Scalar | NumericLiteral | TemporalLiteral, / + ) -> Scalar: ... @overload def __add__(self, other: Any, /) -> Any: ... __sub__ = __add__ @@ -80,7 +83,12 @@ class Scalar(_Weakrefable): @overload def __pow__(self, other: Array, mod: None = None, /) -> Array: ... @overload - def __pow__(self, other: Scalar | float, mod: None = None, /) -> Scalar: ... + def __pow__( + self, + other: Scalar | NumericLiteral | TemporalLiteral, + mod: None = None, + /, + ) -> Scalar: ... @overload def __pow__(self, other: Any, mod: None = None, /) -> Any: ... diff --git a/python/pyarrow-stubs/_stubs_typing.pyi b/python/pyarrow-stubs/_stubs_typing.pyi index 90a79999511e..a3cee2d5ffc8 100644 --- a/python/pyarrow-stubs/_stubs_typing.pyi +++ b/python/pyarrow-stubs/_stubs_typing.pyi @@ -15,7 +15,9 @@ # specific language governing permissions and limitations # under the License. +import datetime as dt from collections.abc import Sequence +from decimal import Decimal from typing import Any, Literal, Protocol, TypeAlias import numpy as np @@ -36,6 +38,11 @@ Indices: TypeAlias = ( Sequence[int | None] | NDArray[np.integer[Any]] | Array | ChunkedArray ) +# Python literals that compute functions and the scalar operators convert to +# scalars. float covers int, np.generic covers NumPy scalars +NumericLiteral: TypeAlias = float | Decimal | np.generic +TemporalLiteral: TypeAlias = dt.date | dt.time | dt.timedelta | np.generic + class SupportsArrowStream(Protocol): def __arrow_c_stream__(self, requested_schema: Any = None, /) -> Any: ... diff --git a/python/pyarrow-stubs/compute.pyi b/python/pyarrow-stubs/compute.pyi index 4da43929519b..cd7b33617d10 100644 --- a/python/pyarrow-stubs/compute.pyi +++ b/python/pyarrow-stubs/compute.pyi @@ -15,10 +15,7 @@ # 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 @@ -126,7 +123,9 @@ from pyarrow._stubs_typing import ( NullEncoding, NullPlacement, NullSelectionBehavior, + NumericLiteral, Order, + TemporalLiteral, TimeUnit, ) from pyarrow.lib import ( @@ -261,11 +260,8 @@ _ScalarOrArray: TypeAlias = Scalar | Array | ChunkedArray _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. -_NumericLiteral: TypeAlias = float | Decimal | np.generic -_TemporalLiteral: TypeAlias = dt.date | dt.time | dt.timedelta | np.generic -_Literal: TypeAlias = _NumericLiteral | _TemporalLiteral | bool | str | bytes +# Python literals that compute functions convert to scalars +_Literal: TypeAlias = NumericLiteral | TemporalLiteral | bool | str | bytes _DecimalArray: TypeAlias = ( Decimal32Array | Decimal64Array | Decimal128Array | Decimal256Array ) @@ -475,7 +471,7 @@ def variance( # ========================= Arithmetic functions ========================= def abs( - x: _ComputeInput | _NumericLiteral | _TemporalLiteral, + x: _ComputeInput | NumericLiteral | TemporalLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -484,8 +480,8 @@ def abs( abs_checked = _clone_signature(abs) def add( - x: _ComputeInput | _NumericLiteral | _TemporalLiteral, - y: _ComputeInput | _NumericLiteral | _TemporalLiteral, + x: _ComputeInput | NumericLiteral | TemporalLiteral, + y: _ComputeInput | NumericLiteral | TemporalLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -494,8 +490,8 @@ def add( add_checked = _clone_signature(add) def divide( - x: _ComputeInput | _NumericLiteral | _TemporalLiteral, - y: _ComputeInput | _NumericLiteral | _TemporalLiteral, + x: _ComputeInput | NumericLiteral | TemporalLiteral, + y: _ComputeInput | NumericLiteral | TemporalLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -504,7 +500,7 @@ def divide( divide_checked = _clone_signature(divide) def exp( - exponent: _ComputeInput | _NumericLiteral, + exponent: _ComputeInput | NumericLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -520,15 +516,15 @@ def exp( expm1 = _clone_signature(exp) def hypot( - x: _ComputeInput | _NumericLiteral, - y: _ComputeInput | _NumericLiteral, + x: _ComputeInput | NumericLiteral, + y: _ComputeInput | NumericLiteral, /, *, memory_pool: MemoryPool | None = None, ) -> _FloatScalar | FloatingPointArray | ChunkedArray | Expression: ... def modulo( - dividend: _ComputeInput | _NumericLiteral, - divisor: _ComputeInput | _NumericLiteral, + dividend: _ComputeInput | NumericLiteral, + divisor: _ComputeInput | NumericLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -539,7 +535,7 @@ multiply = _clone_signature(add) multiply_checked = _clone_signature(add) def negate( - x: _ComputeInput | _NumericLiteral | _TemporalLiteral, + x: _ComputeInput | NumericLiteral | TemporalLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -548,8 +544,8 @@ def negate( negate_checked = _clone_signature(negate) def power( - base: _ComputeInput | _NumericLiteral, - exponent: _ComputeInput | _NumericLiteral, + base: _ComputeInput | NumericLiteral, + exponent: _ComputeInput | NumericLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -560,13 +556,13 @@ remainder = _clone_signature(modulo) remainder_checked = _clone_signature(modulo) def sign( - x: _ComputeInput | _NumericLiteral | _TemporalLiteral, + x: _ComputeInput | NumericLiteral | TemporalLiteral, /, *, memory_pool: MemoryPool | None = None, ) -> Int8Scalar | _FloatScalar | NumericArray | ChunkedArray | Expression: ... def sqrt( - x: _ComputeInput | _NumericLiteral, + x: _ComputeInput | NumericLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -600,7 +596,7 @@ shift_right_checked = _clone_signature(bit_wise_and) # ========================= Rounding functions ========================= def ceil( - x: _ComputeInput | _NumericLiteral, + x: _ComputeInput | NumericLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -616,7 +612,7 @@ def ceil( floor = _clone_signature(ceil) def round( - x: _ComputeInput | _NumericLiteral, + x: _ComputeInput | NumericLiteral, /, ndigits: int = 0, round_mode: _RoundMode = "half_to_even", @@ -625,7 +621,7 @@ def round( memory_pool: MemoryPool | None = None, ) -> _NumericScalar | _NumericArray | ChunkedArray | Expression: ... def round_to_multiple( - x: _ComputeInput | _NumericLiteral, + x: _ComputeInput | NumericLiteral, /, multiple: float | Scalar = 1.0, round_mode: _RoundMode = "half_to_even", @@ -634,7 +630,7 @@ def round_to_multiple( memory_pool: MemoryPool | None = None, ) -> _NumericScalar | _NumericArray | ChunkedArray | Expression: ... def round_binary( - x: _ComputeInput | _NumericLiteral, + x: _ComputeInput | NumericLiteral, s: _ComputeInput | int, /, round_mode: _RoundMode = "half_to_even", @@ -647,7 +643,7 @@ trunc = _clone_signature(ceil) # ========================= Logarithmic functions ========================= def ln( - x: _ComputeInput | _NumericLiteral, + x: _ComputeInput | NumericLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -662,8 +658,8 @@ log2 = _clone_signature(ln) log2_checked = _clone_signature(ln) def logb( - x: _ComputeInput | _NumericLiteral, - b: _ComputeInput | _NumericLiteral, + x: _ComputeInput | NumericLiteral, + b: _ComputeInput | NumericLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -679,8 +675,8 @@ asin_checked = _clone_signature(ln) atan = _clone_signature(ln) def atan2( - y: _ComputeInput | _NumericLiteral, - x: _ComputeInput | _NumericLiteral, + y: _ComputeInput | NumericLiteral, + x: _ComputeInput | NumericLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -1189,7 +1185,7 @@ def cast( memory_pool: MemoryPool | None = None, ) -> Scalar | Array | ChunkedArray: ... def strftime( - timestamps: _ComputeInput | _TemporalLiteral, + timestamps: _ComputeInput | TemporalLiteral, /, format: str | bytes = "%Y-%m-%dT%H:%M:%S", locale: str = "C", @@ -1224,13 +1220,13 @@ def run_end_decode( # ========================= Temporal component extraction ========================= def day( - values: _ComputeInput | _TemporalLiteral, + values: _ComputeInput | TemporalLiteral, /, *, memory_pool: MemoryPool | None = None, ) -> Int64Scalar | Int64Array | ChunkedArray | Expression: ... def day_of_week( - values: _ComputeInput | _TemporalLiteral, + values: _ComputeInput | TemporalLiteral, /, *, count_from_zero: bool = True, @@ -1242,19 +1238,19 @@ def day_of_week( day_of_year = _clone_signature(day) def hour( - values: _ComputeInput | _TemporalLiteral, + values: _ComputeInput | TemporalLiteral, /, *, memory_pool: MemoryPool | None = None, ) -> Int64Scalar | Int64Array | ChunkedArray | Expression: ... def is_dst( - values: _ComputeInput | _TemporalLiteral, + values: _ComputeInput | TemporalLiteral, /, *, memory_pool: MemoryPool | None = None, ) -> BooleanScalar | BooleanArray | ChunkedArray | Expression: ... def iso_week( - values: _ComputeInput | _TemporalLiteral, + values: _ComputeInput | TemporalLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -1263,7 +1259,7 @@ def iso_week( iso_year = _clone_signature(iso_week) def is_leap_year( - values: _ComputeInput | _TemporalLiteral, + values: _ComputeInput | TemporalLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -1278,7 +1274,7 @@ quarter = _clone_signature(day) second = _clone_signature(hour) def subsecond( - values: _ComputeInput | _TemporalLiteral, + values: _ComputeInput | TemporalLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -1288,7 +1284,7 @@ us_week = _clone_signature(iso_week) us_year = _clone_signature(iso_week) def week( - values: _ComputeInput | _TemporalLiteral, + values: _ComputeInput | TemporalLiteral, /, *, week_starts_monday: bool = True, @@ -1301,7 +1297,7 @@ def week( year = _clone_signature(iso_week) def year_month_day( - values: _ComputeInput | _TemporalLiteral, + values: _ComputeInput | TemporalLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -1312,15 +1308,15 @@ iso_calendar = _clone_signature(year_month_day) # ========================= Temporal difference ========================= # TODO(GH-29828): add once PyArrow supports DayTimeInterval type # def day_time_interval_between( -# start: _ComputeInput | _TemporalLiteral, -# end: _ComputeInput | _TemporalLiteral, +# start: _ComputeInput | TemporalLiteral, +# end: _ComputeInput | TemporalLiteral, # /, # *, # memory_pool: MemoryPool | None = None, # ) -> _ScalarOrArray | Expression: ... def days_between( - start: _ComputeInput | _TemporalLiteral, - end: _ComputeInput | _TemporalLiteral, + start: _ComputeInput | TemporalLiteral, + end: _ComputeInput | TemporalLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -1332,8 +1328,8 @@ milliseconds_between = _clone_signature(days_between) minutes_between = _clone_signature(days_between) def month_day_nano_interval_between( - start: _ComputeInput | _TemporalLiteral, - end: _ComputeInput | _TemporalLiteral, + start: _ComputeInput | TemporalLiteral, + end: _ComputeInput | TemporalLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -1343,8 +1339,8 @@ def month_day_nano_interval_between( # TODO(GH-29828): add once PyArrow supports MonthInterval type # def month_interval_between( -# start: _ComputeInput | _TemporalLiteral, -# end: _ComputeInput | _TemporalLiteral, +# start: _ComputeInput | TemporalLiteral, +# end: _ComputeInput | TemporalLiteral, # /, # *, # memory_pool: MemoryPool | None = None, @@ -1355,8 +1351,8 @@ quarters_between = _clone_signature(days_between) seconds_between = _clone_signature(days_between) def weeks_between( - start: _ComputeInput | _TemporalLiteral, - end: _ComputeInput | _TemporalLiteral, + start: _ComputeInput | TemporalLiteral, + end: _ComputeInput | TemporalLiteral, /, *, count_from_zero: bool = True, @@ -1369,7 +1365,7 @@ years_between = _clone_signature(days_between) # ========================= Timezone handling ========================= def assume_timezone( - timestamps: _ComputeInput | _TemporalLiteral, + timestamps: _ComputeInput | TemporalLiteral, /, timezone: str | bytes, *, @@ -1379,7 +1375,7 @@ def assume_timezone( memory_pool: MemoryPool | None = None, ) -> TimestampScalar | TimestampArray | ChunkedArray | Expression: ... def local_timestamp( - values: _ComputeInput | _TemporalLiteral, + values: _ComputeInput | TemporalLiteral, /, *, memory_pool: MemoryPool | None = None, From d609f7fa8a6f9566a632da4bbfebc535dcf5fa08 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Wed, 2 Dec 2026 10:28:17 +0100 Subject: [PATCH 30/35] Widen 7 compute stubs to use _Literal type alias --- python/pyarrow-stubs-tests/test_compute.py | 6 ++++++ python/pyarrow-stubs/compute.pyi | 14 +++++++------- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/python/pyarrow-stubs-tests/test_compute.py b/python/pyarrow-stubs-tests/test_compute.py index ca0160d1fbeb..a9fed0e8ca46 100644 --- a/python/pyarrow-stubs-tests/test_compute.py +++ b/python/pyarrow-stubs-tests/test_compute.py @@ -308,6 +308,9 @@ def test_element_wise_functions() -> None: 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) + check(pc.is_null("a"), pa.BooleanScalar) + check(pc.is_finite(1.5), pa.BooleanScalar) + check(pc.is_nan(1.5), pa.BooleanScalar) # decimal, datetime and numpy also accepted check(pc.sqrt(Decimal("2.25")), pa.DoubleScalar) @@ -387,6 +390,8 @@ def test_element_wise_functions() -> None: 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(2, pa.array([1, 2])), pa.Int32Scalar) + check(pc.is_in("a", pa.array(["a"])), pa.BooleanScalar) 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) @@ -395,6 +400,7 @@ def test_element_wise_functions() -> None: # Conversions check(pc.ceil_temporal([dt.datetime(2026, 11, 23, 10, 17)]), pa.TimestampArray) + check(pc.floor_temporal(dt.datetime(2026, 11, 23, 10, 17)), pa.TimestampScalar) 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) diff --git a/python/pyarrow-stubs/compute.pyi b/python/pyarrow-stubs/compute.pyi index cd7b33617d10..95e7cea35400 100644 --- a/python/pyarrow-stubs/compute.pyi +++ b/python/pyarrow-stubs/compute.pyi @@ -1047,7 +1047,7 @@ find_substring = _clone_signature(count_substring) find_substring_regex = _clone_signature(count_substring) def index_in( - values: _ComputeInput, + values: _ComputeInput | _Literal, /, value_set: _ArrayOrChunkedArray, *, @@ -1056,7 +1056,7 @@ def index_in( memory_pool: MemoryPool | None = None, ) -> Int32Scalar | Int32Array | ChunkedArray | Expression: ... def is_in( - values: _ComputeInput, + values: _ComputeInput | _Literal, /, value_set: _ArrayOrChunkedArray, *, @@ -1087,7 +1087,7 @@ def is_in_meta_binary( # ========================= Categorizations ========================= def is_finite( - values: _ComputeInput, + values: _ComputeInput | NumericLiteral, /, *, memory_pool: MemoryPool | None = None, @@ -1097,7 +1097,7 @@ is_inf = _clone_signature(is_finite) is_nan = _clone_signature(is_finite) def is_null( - values: _ComputeInput, + values: _ComputeInput | _Literal, /, *, nan_is_null: bool = False, @@ -1105,7 +1105,7 @@ def is_null( memory_pool: MemoryPool | None = None, ) -> BooleanScalar | BooleanArray | ChunkedArray | Expression: ... def is_valid( - values: _ComputeInput, + values: _ComputeInput | _Literal, /, *, memory_pool: MemoryPool | None = None, @@ -1152,7 +1152,7 @@ def list_value_length( Int32Scalar | Int64Scalar | Int32Array | Int64Array | ChunkedArray | Expression ): ... def make_struct( - *args: _ComputeInput, + *args: _ComputeInput | _Literal, field_names: Sequence[str] = (), field_nullability: Sequence[bool] | None = None, field_metadata: Sequence[KeyValueMetadata | None] | None = None, @@ -1162,7 +1162,7 @@ def make_struct( # ========================= Conversions ========================= def ceil_temporal( - timestamps: _ComputeInput, + timestamps: _ComputeInput | TemporalLiteral, /, multiple: int = 1, unit: _DateTimeUnit = "day", From 0cbcd7df0276a308d851b07594eb8c13e4a488ce Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Wed, 2 Dec 2026 10:41:09 +0100 Subject: [PATCH 31/35] Rename variables in the tests --- python/pyarrow-stubs-tests/test_compute.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/python/pyarrow-stubs-tests/test_compute.py b/python/pyarrow-stubs-tests/test_compute.py index a9fed0e8ca46..e16d27c44d7d 100644 --- a/python/pyarrow-stubs-tests/test_compute.py +++ b/python/pyarrow-stubs-tests/test_compute.py @@ -360,12 +360,12 @@ def test_element_wise_functions() -> None: 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}) - 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) + struct_array = pc.make_struct([True, False], [False, None]) + check(pc.case_when(struct_array, [1, 2], [12, 13]), pa.Int64Array) + struct_scalar = pa.scalar({"a": False, "b": True}) + check(pc.case_when(struct_scalar, ["foo"], ["bar"]), pa.StringArray) + check(pc.case_when(struct_scalar, 1, 2), pa.Int64Scalar) + check(pc.case_when(struct_scalar, "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) From 37ee98fe0bb8829358e98212ae8907b62d4a6711 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Wed, 2 Dec 2026 11:07:59 +0100 Subject: [PATCH 32/35] Clear TODOs in tests --- python/pyarrow-stubs-tests/test_compute.py | 28 ++++++++++++---------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/python/pyarrow-stubs-tests/test_compute.py b/python/pyarrow-stubs-tests/test_compute.py index e16d27c44d7d..3291a89ccd25 100644 --- a/python/pyarrow-stubs-tests/test_compute.py +++ b/python/pyarrow-stubs-tests/test_compute.py @@ -168,8 +168,7 @@ 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.SetLookupOptions(pa.scalar(2)) # type: ignore[arg-type] pc.SearchSortedOptions(side="middle") # type: ignore[arg-type] _: Hashable = options # type: ignore[assignment] # ty: ignore[invalid-assignment] # noqa: E501 @@ -281,8 +280,8 @@ def test_array_wise_functions() -> None: # 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") + pc.variance(range(3)) # type: ignore[arg-type] + pc.round("abc") # type: ignore[arg-type] def test_element_wise_functions() -> None: @@ -432,11 +431,14 @@ def test_element_wise_functions() -> None: 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 - # 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") + pc.bit_wise_and(1.0, 1.0) # type: ignore[arg-type] + pc.bit_wise_not(1.0) # type: ignore[arg-type] + pc.add("a", 1) # type: ignore[arg-type] + pc.sqrt(dt.timedelta(days=1)) # type: ignore[arg-type] + pc.if_else("yes", 1, 2) # type: ignore[arg-type] + pc.index_in([1, 2, 3], value_set=pa.scalar(2)) # type: ignore[arg-type] + pc.cast(pa.table({"a": [1]}), pa.float32()) # type: ignore[arg-type] + pc.cast(pc.field("a"), "int64") # type: ignore[arg-type] def test_agg_functions() -> None: @@ -469,7 +471,7 @@ def test_agg_functions() -> None: # 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, e.g. evaluating - # pc.sum(pc.field("a")) in ds.dataset(table).to_table(columns=...) fails: - # pc.sum(pc.field("a")) + if TYPE_CHECKING: + # 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")) # type: ignore[arg-type] From 04add2cdab603db026632e43646b2d5e2dc36f09 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Wed, 2 Dec 2026 11:40:32 +0100 Subject: [PATCH 33/35] Add missing assert_type checks in test_compute --- python/pyarrow-stubs-tests/test_compute.py | 573 ++++++++++++++++----- python/pyarrow-stubs/compute.pyi | 9 +- 2 files changed, 452 insertions(+), 130 deletions(-) diff --git a/python/pyarrow-stubs-tests/test_compute.py b/python/pyarrow-stubs-tests/test_compute.py index 3291a89ccd25..1b95de2836a1 100644 --- a/python/pyarrow-stubs-tests/test_compute.py +++ b/python/pyarrow-stubs-tests/test_compute.py @@ -24,19 +24,137 @@ import pyarrow as pa import pyarrow.compute as pc -from pyarrow.lib import Buffer +from pyarrow.lib import BaseListArray, Buffer from _check import assert_type, check -_Filtered: TypeAlias = pa.Array | pa.ChunkedArray | pa.RecordBatch | pa.Table - -_Quantile: TypeAlias = ( - pa.NumericArray - | pa.Decimal32Array +# Result types of the compute functions, built like the private aliases in +# compute.pyi. +_IntegerScalar: TypeAlias = ( + pa.Int8Scalar + | pa.Int16Scalar + | pa.Int32Scalar + | pa.Int64Scalar + | pa.UInt8Scalar + | pa.UInt16Scalar + | pa.UInt32Scalar + | pa.UInt64Scalar +) +_FloatScalar: TypeAlias = pa.HalfFloatScalar | pa.FloatScalar | pa.DoubleScalar +_DecimalScalar: TypeAlias = ( + pa.Decimal32Scalar + | pa.Decimal64Scalar + | pa.Decimal128Scalar + | pa.Decimal256Scalar +) +_NumericScalar: TypeAlias = _IntegerScalar | _FloatScalar | _DecimalScalar +_TemporalScalar: TypeAlias = ( + pa.Date32Scalar + | pa.Date64Scalar + | pa.Time32Scalar + | pa.Time64Scalar + | pa.TimestampScalar + | pa.DurationScalar + | pa.MonthDayNanoIntervalScalar +) +_StringScalar: TypeAlias = pa.StringScalar | pa.LargeStringScalar | pa.StringViewScalar +_BinaryScalar: TypeAlias = ( + pa.BinaryScalar + | pa.LargeBinaryScalar + | pa.BinaryViewScalar + | pa.FixedSizeBinaryScalar +) +_ListScalar: TypeAlias = ( + pa.ListScalar + | pa.LargeListScalar + | pa.ListViewScalar + | pa.LargeListViewScalar + | pa.FixedSizeListScalar +) +_TemporalArray: TypeAlias = ( + pa.Date32Array + | pa.Date64Array + | pa.Time32Array + | pa.Time64Array + | pa.TimestampArray + | pa.DurationArray + | pa.MonthDayNanoIntervalArray +) +_DecimalArray: TypeAlias = ( + pa.Decimal32Array | pa.Decimal64Array | pa.Decimal128Array | pa.Decimal256Array ) +_StringArray: TypeAlias = pa.StringArray | pa.LargeStringArray | pa.StringViewArray +_BinaryArray: TypeAlias = ( + pa.BinaryArray + | pa.LargeBinaryArray + | pa.BinaryViewArray + | pa.FixedSizeBinaryArray +) +# Every compute function returns these for chunked array or expression input +_Out: TypeAlias = pa.ChunkedArray | pc.Expression + +_FloatResult: TypeAlias = _FloatScalar | pa.FloatingPointArray | _Out +_FloatOrDecimalResult: TypeAlias = ( + _FloatScalar + | _DecimalScalar + | pa.FloatingPointArray + | _DecimalArray + | _Out +) +_NumericResult: TypeAlias = _NumericScalar | pa.NumericArray | _DecimalArray | _Out +_NumericOrDurationResult: TypeAlias = ( + _NumericScalar + | pa.DurationScalar + | pa.NumericArray + | _DecimalArray + | _Out +) +_NumericOrTemporalResult: TypeAlias = ( + _NumericScalar + | _TemporalScalar + | pa.NumericArray + | _DecimalArray + | pa.MonthDayNanoIntervalArray + | _Out +) +_NumericTemporalOrBinaryResult: TypeAlias = ( + _NumericScalar + | _TemporalScalar + | _StringScalar + | _BinaryScalar + | pa.NumericArray + | _DecimalArray + | pa.MonthDayNanoIntervalArray + | _StringArray + | _BinaryArray + | _Out +) +_TemporalResult: TypeAlias = _TemporalScalar | _TemporalArray | _Out +_StringResult: TypeAlias = _StringScalar | _StringArray | _Out +_StringOrBinaryResult: TypeAlias = ( + _StringScalar + | _BinaryScalar + | _StringArray + | _BinaryArray + | _Out +) +_ListResult: TypeAlias = _ListScalar | BaseListArray | _Out +_Int32Or64Result: TypeAlias = ( + pa.Int32Scalar + | pa.Int64Scalar + | pa.Int32Array + | pa.Int64Array + | _Out +) +_BooleanResult: TypeAlias = pa.BooleanScalar | pa.BooleanArray | _Out +_ScalarOrArrayResult: TypeAlias = pa.Scalar | pa.Array | _Out + +_Filtered: TypeAlias = pa.Array | pa.ChunkedArray | pa.RecordBatch | pa.Table + +_Quantile: TypeAlias = pa.NumericArray | _DecimalArray _Numeric: TypeAlias = ( pa.NumericArray @@ -75,8 +193,8 @@ def test_expression() -> None: check(assert_type(field.equals(pc.field("a")), bool), bool) # Element-wise compute functions on an expression build an expression - check(pc.abs(field), pc.Expression) - check(pc.utf8_upper(field), pc.Expression) + check(assert_type(pc.abs(field), _NumericOrDurationResult), pc.Expression) + check(assert_type(pc.utf8_upper(field), _StringResult), pc.Expression) if TYPE_CHECKING: # Expressions define __eq__ and are unhashable. @@ -239,9 +357,17 @@ def test_array_wise_functions() -> None: 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_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_contains([[1, 2, 3]], 1), _BooleanResult), + pa.BooleanArray) + check( + assert_type( + pc.list_contains(pa.chunked_array([[[1, 2, 3]]]), 1), + _BooleanResult, + ), + pa.ChunkedArray, + ) + check(assert_type(pc.list_element([[1, 2, 3]], 1), _ScalarOrArrayResult), + 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), @@ -249,8 +375,15 @@ 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) + check(assert_type(pc.list_slice(pa.scalar([1, 2, 3]), 1), _ListResult), + pa.ListScalar) + check( + assert_type( + pc.struct_field(pa.array([{"a": 1}]), ("a",)), + _ScalarOrArrayResult, + ), + pa.Array, + ) # Replace functions always return arrays check(assert_type(pc.fill_null_forward([1, None]), pa.Array | pa.ChunkedArray), @@ -261,8 +394,20 @@ def test_array_wise_functions() -> None: 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) + check( + assert_type( + pc.replace_with_mask(arr, mask, pa.scalar(10)), + pa.Array | pa.ChunkedArray, + ), + pa.Int64Array, + ) + check( + assert_type( + pc.replace_with_mask(arr, mask, [10, 30]), + pa.Array | pa.ChunkedArray, + ), + pa.Int64Array, + ) # Pairwise functions check(assert_type(pc.pairwise_diff([1, 3, 6]), _NumericOrTemporal), pa.Int64Array) @@ -291,121 +436,274 @@ def test_element_wise_functions() -> None: check(assert_type(pc.random(3), pa.DoubleArray), pa.DoubleArray) # 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) - 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.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) - check(pc.is_valid([1.1]), pa.BooleanArray) - check(pc.true_unless_null(1.1), pa.BooleanScalar) - check(pc.is_null("a"), pa.BooleanScalar) - check(pc.is_finite(1.5), pa.BooleanScalar) - check(pc.is_nan(1.5), pa.BooleanScalar) + check(assert_type(pc.abs([1, 2]), _NumericOrDurationResult), pa.Int64Array) + check(assert_type(pc.abs((1.5, -2.5)), _NumericOrDurationResult), pa.DoubleArray) + check(assert_type(pc.abs(1), _NumericOrDurationResult), pa.Int64Scalar) + check(assert_type(pc.abs_checked(-2.5), _NumericOrDurationResult), pa.DoubleScalar) + check(assert_type(pc.add(-2.5, 1.5), _NumericOrTemporalResult), pa.DoubleScalar) + check(assert_type(pc.add_checked([2.5, 3.5], 1), _NumericOrTemporalResult), + pa.DoubleArray) + check(assert_type(pc.exp(2.5), _FloatResult), pa.DoubleScalar) + check(assert_type(pc.exp([1, 2]), _FloatResult), pa.DoubleArray) + check(assert_type(pc.divide([1, 2, 3], 1), _NumericOrTemporalResult), pa.Int64Array) + check(assert_type(pc.divide(arr, 2.5), _NumericOrTemporalResult), pa.Array) + check(assert_type(pc.hypot([1, 2, 3], 1), _FloatResult), pa.DoubleArray) + check(assert_type(pc.modulo([7, -7], [3, 3]), _NumericResult), pa.Int64Array) + check(assert_type(pc.power(arr, 2), _NumericResult), pa.Array) + check(assert_type(pc.sqrt(pa.chunked_array([[1], [2, 3]])), _FloatResult), + pa.ChunkedArray) + check(assert_type(pc.is_valid([1.1]), _BooleanResult), pa.BooleanArray) + check(assert_type(pc.true_unless_null(1.1), _BooleanResult), pa.BooleanScalar) + check(assert_type(pc.is_null("a"), _BooleanResult), pa.BooleanScalar) + check(assert_type(pc.is_finite(1.5), _BooleanResult), pa.BooleanScalar) + check(assert_type(pc.is_nan(1.5), _BooleanResult), 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) - check(pc.add(arr, np.int64(1)), pa.Int64Array) + check(assert_type(pc.sqrt(Decimal("2.25")), _FloatResult), pa.DoubleScalar) + check( + assert_type( + pc.add(dt.datetime(2026, 1, 1), dt.timedelta(days=1)), + _NumericOrTemporalResult, + ), + pa.TimestampScalar, + ) + check(assert_type(pc.add(arr, np.int64(1)), _NumericOrTemporalResult), + pa.Int64Array) # Bit-wise functions - check(pc.bit_wise_and([1, 1], [1, 1]), pa.Int64Array) - check(pc.bit_wise_not([1, 1]), pa.Int64Array) + check(assert_type(pc.bit_wise_and([1, 1], [1, 1]), _NumericResult), pa.Int64Array) + check(assert_type(pc.bit_wise_not([1, 1]), _NumericResult), 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) - check(pc.round((1.5, 2.5)), pa.Array) - check(pc.round([1.5, 2.5]), pa.Array) + check(assert_type(pc.ceil(1.5), _FloatOrDecimalResult), pa.DoubleScalar) + check(assert_type(pc.floor([1, 2]), _FloatOrDecimalResult), pa.DoubleArray) + check(assert_type(pc.trunc(pa.scalar(Decimal("1.5"))), _FloatOrDecimalResult), + pa.Decimal128Scalar) + check(assert_type(pc.trunc(pa.array([Decimal("1.5")])), _FloatOrDecimalResult), + pa.Decimal128Array) + check(assert_type(pc.round((1.5, 2.5)), _NumericResult), pa.Array) + check(assert_type(pc.round([1.5, 2.5]), _NumericResult), pa.Array) # Logarithms return floats - check(pc.ln(pa.array([Decimal("1.5")])), pa.DoubleArray) + check(assert_type(pc.ln(pa.array([Decimal("1.5")])), _FloatResult), 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) - check(pc.acos([1.1, 1.1]), pa.DoubleArray) - check(pc.atan2([1.1, 1.1], [1.1, 1.1]), pa.DoubleArray) + check(assert_type(pc.sin([1, 2]), _FloatResult), pa.DoubleArray) + check(assert_type(pc.acos(0.5), _FloatResult), pa.DoubleScalar) + check(assert_type(pc.atan2(1.5, [1, 2]), _FloatResult), pa.DoubleArray) + check(assert_type(pc.cosh(pa.array([Decimal("1.5")])), _FloatResult), + pa.DoubleArray) + check(assert_type(pc.acos([1.1, 1.1]), _FloatResult), pa.DoubleArray) + check(assert_type(pc.atan2([1.1, 1.1], [1.1, 1.1]), _FloatResult), pa.DoubleArray) # 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) + check(assert_type(pc.equal(pa.scalar("a"), "a"), _BooleanResult), pa.BooleanScalar) + check(assert_type(pc.equal(True, False), _BooleanResult), pa.BooleanScalar) + check( + assert_type( + pc.max_element_wise(pa.array(["a", "b"]), "c"), + _NumericTemporalOrBinaryResult, + ), + pa.StringArray, + ) + check( + assert_type( + pc.less(dt.datetime(2026, 1, 1), dt.datetime(2026, 1, 2)), + _BooleanResult, + ), + pa.BooleanScalar, + ) + check(assert_type(pc.greater_equal(1.1, 2.2), _BooleanResult), pa.BooleanScalar) + check(assert_type(pc.if_else(True, 1, 2), _ScalarOrArrayResult), 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) # 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) - - check(pc.make_struct(1, 'a', field_nullability=[True]), pa.StructScalar) - check(pc.make_struct(1, 'a', field_metadata=[None]), pa.StructScalar) + check(assert_type(pc.if_else(pc.field("a") > 1, 1, 2), _ScalarOrArrayResult), + pc.Expression) + check(assert_type(pc.if_else(np.bool_(True), 1, 2), _ScalarOrArrayResult), + pa.Int64Scalar) + check(assert_type(pc.choose(1, [1, 2], [3, 4]), _ScalarOrArrayResult), + pa.Int64Array) + check( + assert_type( + pc.fill_null(pa.array([1, None]), 5), + pa.Scalar | pa.Array | pa.ChunkedArray, + ), + pa.Int64Array, + ) + check(assert_type(pc.equal([1, 2, 1], [1, 2, 3]), _BooleanResult), pa.BooleanArray) + + check( + assert_type( + pc.make_struct(1, 'a', field_nullability=[True]), + pa.StructScalar | pa.StructArray | _Out, + ), + pa.StructScalar, + ) + check( + assert_type( + pc.make_struct(1, 'a', field_metadata=[None]), + pa.StructScalar | pa.StructArray | _Out, + ), + pa.StructScalar, + ) struct_array = pc.make_struct([True, False], [False, None]) - check(pc.case_when(struct_array, [1, 2], [12, 13]), pa.Int64Array) + check( + assert_type(pc.case_when(struct_array, [1, 2], [12, 13]), _ScalarOrArrayResult), + pa.Int64Array, + ) struct_scalar = pa.scalar({"a": False, "b": True}) - check(pc.case_when(struct_scalar, ["foo"], ["bar"]), pa.StringArray) - check(pc.case_when(struct_scalar, 1, 2), pa.Int64Scalar) - check(pc.case_when(struct_scalar, "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) + check( + assert_type( + pc.case_when(struct_scalar, ["foo"], ["bar"]), + _ScalarOrArrayResult, + ), + pa.StringArray, + ) + check(assert_type(pc.case_when(struct_scalar, 1, 2), _ScalarOrArrayResult), + pa.Int64Scalar) + check(assert_type(pc.case_when(struct_scalar, "a", "b"), _ScalarOrArrayResult), + pa.StringScalar) + check( + assert_type( + pc.case_when([{"a": True, "b": False}], [1.1], [3.3]), + _ScalarOrArrayResult, + ), + pa.DoubleArray, + ) + check(assert_type(pc.choose([1, 2, 1], "a", "b", "c"), _ScalarOrArrayResult), + pa.StringArray) # Logical functions - check(pc.and_not([True], [False]), pa.BooleanArray) + check(assert_type(pc.and_not([True], [False]), _BooleanResult), 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) + check(assert_type(pc.utf8_is_space([" "]), _BooleanResult), pa.BooleanArray) + check(assert_type(pc.binary_repeat(pa.array(["a"]), (2,)), _StringOrBinaryResult), + pa.Array) + check(assert_type(pc.binary_repeat(b"foozfoo", [3]), _StringOrBinaryResult), + pa.BinaryArray) + check( + assert_type( + pc.replace_substring(b"foozfoo", "foo", "bar"), + _StringOrBinaryResult, + ), + pa.BinaryScalar, + ) + check(assert_type(pc.ascii_ltrim(["foozfoo"], b"foo"), _StringResult), + pa.StringArray) + check(assert_type(pc.split_pattern([b"foozfoo"], b"t"), _ListResult), pa.ListArray) + check( + assert_type( + pc.extract_regex(b"a1", rb"(?P[ab])(?P\d)"), + pa.StructScalar | pa.StructArray | _Out, + ), + pa.StructScalar, + ) + check(assert_type(pc.binary_join([["a", "b"], ["c"]], "-"), _StringOrBinaryResult), + pa.StringArray) + check( + assert_type( + pc.binary_join(pc.field("a"), pc.field("sep")), + _StringOrBinaryResult, + ), + pc.Expression, + ) + check( + assert_type( + pc.binary_join_element_wise(["a", "b"], ["c", "d"], "-"), + _StringOrBinaryResult, + ), + 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(2, pa.array([1, 2])), pa.Int32Scalar) - check(pc.is_in("a", pa.array(["a"])), pa.BooleanScalar) - 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) + check(assert_type(pc.count_substring([b"abcab"], "ab"), _Int32Or64Result), + pa.Int32Array) + check(assert_type(pc.ends_with([b"abcab"], "ab"), _BooleanResult), pa.BooleanArray) + check( + assert_type( + pc.index_in([1, 2, 3], pa.array([1, 2])), + pa.Int32Scalar | pa.Int32Array | _Out, + ), + pa.Int32Array, + ) + check(assert_type(pc.is_in([1, 2, 3], pa.array([1, 2])), _BooleanResult), + pa.BooleanArray) + check( + assert_type( + pc.index_in(2, pa.array([1, 2])), + pa.Int32Scalar | pa.Int32Array | _Out, + ), + pa.Int32Scalar, + ) + check(assert_type(pc.is_in("a", pa.array(["a"])), _BooleanResult), pa.BooleanScalar) + check( + assert_type( + pc.index_in_meta_binary([1, 2, 3], [1, 2]), + pa.Int32Scalar | pa.Int32Array | pa.ChunkedArray, + ), + pa.Int32Array, + ) + check( + assert_type( + pc.is_in_meta_binary([1, 2, 3], [1, 2]), + pa.BooleanScalar | pa.BooleanArray | pa.ChunkedArray, + ), + pa.BooleanArray, + ) # Structural transforms - check(pc.list_value_length([[1], [1, 2]]), pa.Int32Array) + check(assert_type(pc.list_value_length([[1], [1, 2]]), _Int32Or64Result), + pa.Int32Array) # Conversions - check(pc.ceil_temporal([dt.datetime(2026, 11, 23, 10, 17)]), pa.TimestampArray) - check(pc.floor_temporal(dt.datetime(2026, 11, 23, 10, 17)), pa.TimestampScalar) - 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) + check( + assert_type( + pc.ceil_temporal([dt.datetime(2026, 11, 23, 10, 17)]), + _TemporalResult, + ), + pa.TimestampArray, + ) + check( + assert_type( + pc.floor_temporal(dt.datetime(2026, 11, 23, 10, 17)), + _TemporalResult, + ), + pa.TimestampScalar, + ) + check(assert_type(pc.cast(1, pa.float32()), pa.Scalar | pa.Array | pa.ChunkedArray), + pa.FloatScalar) + check( + assert_type( + pc.strftime(dt.datetime(2026, 11, 23), format="%Y-%m-%d"), + pa.StringScalar | pa.StringArray | _Out, + ), + pa.StringScalar, + ) + check( + assert_type( + pc.strftime(pc.field("ts"), format=b"%Y-%m-%d"), + pa.StringScalar | pa.StringArray | _Out, + ), + pc.Expression, + ) + check( + assert_type( + pc.strptime(["5/1/2020", None, "12/13/1900"], format='%m/%d/%Y', unit='s'), + pa.TimestampScalar | pa.TimestampArray | _Out, + ), + pa.TimestampArray, + ) + check( + assert_type( + pc.strptime("5/1/2020", format=b'%m/%d/%Y', unit='s'), + pa.TimestampScalar | pa.TimestampArray | _Out, + ), + 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) @@ -413,17 +711,47 @@ def test_element_wise_functions() -> None: # Temporal 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]), - 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) + check(assert_type(pc.day(date), pa.Int64Scalar | pa.Int64Array | _Out), + pa.Int64Scalar) + check(assert_type(pc.day([date]), pa.Int64Scalar | pa.Int64Array | _Out), + pa.Int64Array) + check(assert_type(pc.hour(date), pa.Int64Scalar | pa.Int64Array | _Out), + pa.Int64Scalar) + check(assert_type(pc.subsecond(date), pa.DoubleScalar | pa.DoubleArray | _Out), + pa.DoubleScalar) + check(assert_type(pc.is_leap_year((date,)), _BooleanResult), pa.BooleanArray) + check( + assert_type(pc.days_between(date, date), pa.Int64Scalar | pa.Int64Array | _Out), + pa.Int64Scalar, + ) + check( + assert_type( + pc.month_day_nano_interval_between([date], [date]), + pa.MonthDayNanoIntervalScalar | pa.MonthDayNanoIntervalArray | _Out, + ), + pa.MonthDayNanoIntervalArray, + ) + check( + assert_type( + pc.years_between((date, ), (date, )), + pa.Int64Scalar | pa.Int64Array | _Out, + ), + pa.Int64Array, + ) + check( + assert_type( + pc.assume_timezone([date], timezone=b"UTC"), + pa.TimestampScalar | pa.TimestampArray | _Out, + ), + pa.TimestampArray, + ) + check( + assert_type( + pc.local_timestamp(date), + pa.TimestampScalar | pa.TimestampArray | _Out, + ), + pa.TimestampScalar, + ) if TYPE_CHECKING: pc.is_in([1, 2, 3], pc.field("a")) # type: ignore[arg-type] @@ -448,11 +776,11 @@ def test_agg_functions() -> None: 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(scalar), pa.StructScalar) + check(assert_type(pc.count(scalar), pa.Int64Scalar), pa.Int64Scalar) + check(assert_type(pc.count_distinct(scalar), pa.Int64Scalar), pa.Int64Scalar) + check(assert_type(pc.first(scalar), pa.Scalar), pa.Int64Scalar) + check(assert_type(pc.last(scalar), pa.Scalar), pa.Int64Scalar) + check(assert_type(pc.first_last(scalar), pa.StructScalar), pa.StructScalar) # Aggregations return no expression check(assert_type(pc.mode(arr, n=2), pa.StructArray), pa.StructArray) @@ -463,13 +791,14 @@ def test_agg_functions() -> None: pa.Int64Array) # 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) - check(pc.first_last((1, 2)), pa.StructScalar) + check(assert_type(pc.variance([1, 2, 3]), pa.DoubleScalar), pa.DoubleScalar) + check(assert_type(pc.variance((1, 2, 3)), pa.DoubleScalar), pa.DoubleScalar) + check(assert_type(pc.variance(np.array([1.0, 2.0, 3.0])), pa.DoubleScalar), + pa.DoubleScalar) + check(assert_type(pc.first_last((1, 2)), pa.StructScalar), pa.StructScalar) # A Python value accepted - check(pc.index(arr, 2), pa.Int64Scalar) + check(assert_type(pc.index(arr, 2), pa.Int64Scalar), pa.Int64Scalar) if TYPE_CHECKING: # Aggregations can't be evaluated as expressions, e.g. evaluating diff --git a/python/pyarrow-stubs/compute.pyi b/python/pyarrow-stubs/compute.pyi index 95e7cea35400..e275990553c4 100644 --- a/python/pyarrow-stubs/compute.pyi +++ b/python/pyarrow-stubs/compute.pyi @@ -504,14 +504,7 @@ def exp( /, *, memory_pool: MemoryPool | None = None, -) -> ( - FloatingPointArray - | ChunkedArray - | DoubleArray - | _FloatScalar - | DoubleScalar - | Expression -): ... +) -> FloatingPointArray | _FloatScalar | ChunkedArray | Expression: ... expm1 = _clone_signature(exp) From b4d57920b7f968b9e392e45d122ae08be9395e03 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Wed, 2 Dec 2026 12:43:50 +0100 Subject: [PATCH 34/35] Update scalar import in _compute.pyi also --- python/pyarrow-stubs/_compute.pyi | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/python/pyarrow-stubs/_compute.pyi b/python/pyarrow-stubs/_compute.pyi index ad7e7b8a1b5d..60b55ff5a53d 100644 --- a/python/pyarrow-stubs/_compute.pyi +++ b/python/pyarrow-stubs/_compute.pyi @@ -19,10 +19,9 @@ from collections.abc import Callable, Hashable, Iterable, Sequence from types import EllipsisType 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. +# 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 Scalar from pyarrow._stubs_typing import ( NullEncoding, NullPlacement, @@ -37,6 +36,7 @@ from pyarrow.lib import ( DataType, KeyValueMetadata, MemoryPool, + Scalar, Schema, _Weakrefable, ) From 03940265e9828aead48c61e27f3fa3819bc141d8 Mon Sep 17 00:00:00 2001 From: AlenkaF Date: Thu, 3 Dec 2026 06:15:10 +0100 Subject: [PATCH 35/35] Resolve TODO(GH-29828) --- python/pyarrow-stubs-tests/test_compute.py | 14 +++++++++ python/pyarrow-stubs/compute.pyi | 35 +++++++++++----------- 2 files changed, 32 insertions(+), 17 deletions(-) diff --git a/python/pyarrow-stubs-tests/test_compute.py b/python/pyarrow-stubs-tests/test_compute.py index 1b95de2836a1..c79274a341c4 100644 --- a/python/pyarrow-stubs-tests/test_compute.py +++ b/python/pyarrow-stubs-tests/test_compute.py @@ -731,6 +731,20 @@ def test_element_wise_functions() -> None: ), pa.MonthDayNanoIntervalArray, ) + check( + assert_type( + pc.month_interval_between([date], [date]), + pa.MonthIntervalScalar | pa.MonthIntervalArray | _Out, + ), + pa.MonthIntervalArray, + ) + check( + assert_type( + pc.day_time_interval_between(date, date), + pa.DayTimeIntervalScalar | pa.DayTimeIntervalArray | _Out, + ), + pa.DayTimeIntervalScalar, + ) check( assert_type( pc.years_between((date, ), (date, )), diff --git a/python/pyarrow-stubs/compute.pyi b/python/pyarrow-stubs/compute.pyi index e275990553c4..79a92a48eb9f 100644 --- a/python/pyarrow-stubs/compute.pyi +++ b/python/pyarrow-stubs/compute.pyi @@ -143,6 +143,8 @@ from pyarrow.lib import ( Date32Scalar, Date64Array, Date64Scalar, + DayTimeIntervalArray, + DayTimeIntervalScalar, Decimal32Array, Decimal32Scalar, Decimal64Array, @@ -181,6 +183,8 @@ from pyarrow.lib import ( MemoryPool, MonthDayNanoIntervalArray, MonthDayNanoIntervalScalar, + MonthIntervalArray, + MonthIntervalScalar, NumericArray, RecordBatch, RunEndEncodedArray, @@ -1299,14 +1303,13 @@ def year_month_day( iso_calendar = _clone_signature(year_month_day) # ========================= Temporal difference ========================= -# 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 day_time_interval_between( + start: _ComputeInput | TemporalLiteral, + end: _ComputeInput | TemporalLiteral, + /, + *, + memory_pool: MemoryPool | None = None, +) -> DayTimeIntervalScalar | DayTimeIntervalArray | ChunkedArray | Expression: ... def days_between( start: _ComputeInput | TemporalLiteral, end: _ComputeInput | TemporalLiteral, @@ -1329,15 +1332,13 @@ def month_day_nano_interval_between( ) -> ( MonthDayNanoIntervalScalar | MonthDayNanoIntervalArray | ChunkedArray | 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: ... +def month_interval_between( + start: _ComputeInput | TemporalLiteral, + end: _ComputeInput | TemporalLiteral, + /, + *, + memory_pool: MemoryPool | None = None, +) -> MonthIntervalScalar | MonthIntervalArray | ChunkedArray | Expression: ... nanoseconds_between = _clone_signature(days_between) quarters_between = _clone_signature(days_between)