diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index bda8967e30d..b678fe403b7 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 b361f3157c9..8346228c95c 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 00000000000..44309f20b92 --- /dev/null +++ b/python/pyarrow-stubs-tests/test_acero.py @@ -0,0 +1,51 @@ +# 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 ( # noqa: E402 + AggregateNodeOptions, + Declaration, + TableSourceNodeOptions, +) + + +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] + + +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-tests/test_compute.py b/python/pyarrow-stubs-tests/test_compute.py new file mode 100644 index 00000000000..c79274a341c --- /dev/null +++ b/python/pyarrow-stubs-tests/test_compute.py @@ -0,0 +1,820 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +import datetime as dt + +from collections.abc import Hashable +from decimal import Decimal +from types import EllipsisType +from typing import TYPE_CHECKING, TypeAlias + +import pyarrow as pa +import pyarrow.compute as pc +from pyarrow.lib import BaseListArray, Buffer + +from _check import assert_type, check + +# 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 + | pa.Decimal32Array + | pa.Decimal64Array + | pa.Decimal128Array + | pa.Decimal256Array + | pa.ChunkedArray +) + +_NumericOrTemporal: TypeAlias = _Quantile | pa.MonthDayNanoIntervalArray + + +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) + 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) + + # Element-wise compute functions on an expression build an 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. + _: 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_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(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: + 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) + + 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: + # 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), + pc.MakeStructOptions) + check(assert_type(pc.StructFieldOptions((0, 1)), pc.StructFieldOptions), + pc.StructFieldOptions) + check(assert_type(pc.StructFieldOptions(["a", "b"]), pc.StructFieldOptions), + pc.StructFieldOptions) + + # Other parameter types: ChunkedArray value set, hashable seed, Literals + 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 can be serialized + 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.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 + + +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 | 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), + pa.UInt64Array) + check(assert_type(pc.sort_indices(table, [(0, "descending")]), + 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), + pa.UInt64Array) + check(assert_type(pc.value_counts(arr), pa.StructArray), + pa.StructArray) + + # 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) + + # Python lists and tuples accepted + 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.UInt64Array) + 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(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), + pa.Int64Array) + check(assert_type(pc.list_parent_indices(pa.chunked_array([[[1, 2], [3]]])), + pa.Int64Array | pa.ChunkedArray), + pa.ChunkedArray) + 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), + 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( + 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) + + 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] + # 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) + 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] + pc.variance(range(3)) # type: ignore[arg-type] + pc.round("abc") # type: ignore[arg-type] + + +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) + + # Python literals, lists and tuples accepted + 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(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(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(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(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(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(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(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( + assert_type(pc.case_when(struct_array, [1, 2], [12, 13]), _ScalarOrArrayResult), + pa.Int64Array, + ) + struct_scalar = pa.scalar({"a": False, "b": True}) + 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(assert_type(pc.and_not([True], [False]), _BooleanResult), pa.BooleanArray) + + # String functions + 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(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(assert_type(pc.list_value_length([[1], [1, 2]]), _Int32Or64Result), + pa.Int32Array) + + # Conversions + 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) + check(assert_type(pc.run_end_decode(ree), pa.Array | pa.ChunkedArray), pa.Array) + + # Temporal + date = dt.datetime(2026, 1, 1) + 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.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, )), + 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] + 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] + 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: + import numpy as np + + arr = pa.array([3, 1, 2]) + scalar = pa.scalar(1) + + # Scalar input accepted + 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) + + # 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) + + # Python lists, tuples and NumPy arrays accepted + 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(assert_type(pc.index(arr, 2), pa.Int64Scalar), pa.Int64Scalar) + + 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] diff --git a/python/pyarrow-stubs-tests/test_scalar.py b/python/pyarrow-stubs-tests/test_scalar.py index e27a2229680..4f2651e622b 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 f206434db26..50804b0eceb 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/_acero.pyi b/python/pyarrow-stubs/_acero.pyi new file mode 100644 index 00000000000..b148ffe7f8d --- /dev/null +++ b/python/pyarrow-stubs/_acero.pyi @@ -0,0 +1,114 @@ +# 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 +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] + +_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 3108cb06374..60b55ff5a53 100644 --- a/python/pyarrow-stubs/_compute.pyi +++ b/python/pyarrow-stubs/_compute.pyi @@ -15,11 +15,541 @@ # 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, Sequence +from types import EllipsisType +from typing import Any, ClassVar, Literal, Protocol, TypeAlias, TypedDict -from typing import Any, 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._stubs_typing import ( + NullEncoding, + NullPlacement, + NullSelectionBehavior, + Order, + TimeUnit, +) +from pyarrow.lib import ( + Array, + Buffer, + ChunkedArray, + DataType, + KeyValueMetadata, + MemoryPool, + Scalar, + 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 | 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"] -def __getattr__(name: str) -> Any: ... +# ==================== Kernels and functions ==================== + +class Kernel(_Weakrefable): ... +class ScalarKernel(Kernel): ... +class VectorKernel(Kernel): ... +class ScalarAggregateKernel(Kernel): ... +class HashAggregateKernel(Kernel): ... + +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 ScalarFunction(Function): + @property + def kernels(self) -> list[ScalarKernel]: ... + +class VectorFunction(Function): + @property + def kernels(self) -> list[VectorKernel]: ... + +class ScalarAggregateFunction(Function): + @property + def kernels(self) -> list[ScalarAggregateKernel]: ... + +class HashAggregateFunction(Function): + @property + def kernels(self) -> list[HashAggregateKernel]: ... + +class MetaFunction(Function): + @property + def kernels(self) -> list[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 FunctionOptions(_Weakrefable): + __hash__: ClassVar[None] # type: ignore[assignment] + + def serialize(self) -> Buffer: ... + @staticmethod + def deserialize(buf: Buffer) -> FunctionOptions: ... + +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 | str | 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 | str | None = None) -> CastOptions: ... + @staticmethod + def unsafe(target_type: DataType | str | None = None) -> CastOptions: ... + def is_safe(self) -> bool: ... + +class ElementWiseAggregateOptions(FunctionOptions): + def __init__(self, *, skip_nulls: bool = True) -> None: ... + +class RoundOptions(FunctionOptions): + def __init__( + self, ndigits: int = 0, round_mode: _RoundMode = "half_to_even" + ) -> None: ... + +class RoundBinaryOptions(FunctionOptions): + def __init__(self, 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 JoinOptions(FunctionOptions): + def __init__( + self, + null_handling: _NullHandling = "emit_null", + null_replacement: str = "", + ) -> 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: ... + +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 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 ScatterOptions(FunctionOptions): + def __init__(self, max_index: int = -1) -> None: ... + +class TakeOptions(FunctionOptions): + def __init__(self, *, boundscheck: bool = True) -> None: ... + +class MakeStructOptions(FunctionOptions): + def __init__( + self, + field_names: Sequence[str] = (), + *, + field_nullability: Sequence[bool] | None = None, + 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 ModeOptions(FunctionOptions): + def __init__( + self, n: int = 1, *, skip_nulls: bool = True, min_count: int = 0 + ) -> None: ... + +class SetLookupOptions(FunctionOptions): + def __init__( + self, value_set: Array | ChunkedArray, *, skip_nulls: bool = False + ) -> None: ... + +class StrptimeOptions(FunctionOptions): + def __init__( + self, format: str, unit: TimeUnit, error_is_null: bool = False + ) -> None: ... + +class StrftimeOptions(FunctionOptions): + def __init__( + self, format: str = "%Y-%m-%dT%H:%M:%S", locale: str = "C" + ) -> None: ... + +class DayOfWeekOptions(FunctionOptions): + def __init__( + self, *, count_from_zero: bool = True, week_start: int = 1 + ) -> 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 AssumeTimezoneOptions(FunctionOptions): + def __init__( + self, + timezone: str, + *, + ambiguous: _TimezoneResolution = "raise", + nonexistent: _TimezoneResolution = "raise", + ) -> None: ... + +class NullOptions(FunctionOptions): + def __init__(self, *, nan_is_null: bool = False) -> 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 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 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 CumulativeOptions(FunctionOptions): + def __init__( + self, start: Scalar | None = None, *, skip_nulls: bool = False + ) -> None: ... + +class PairwiseOptions(FunctionOptions): + def __init__(self, period: int = 1) -> None: ... + +class ListFlattenOptions(FunctionOptions): + def __init__(self, recursive: bool = False) -> None: ... + +class ArraySortOptions(FunctionOptions): + def __init__( + self, + order: Order = "ascending", + *, + null_placement: NullPlacement = "at_end", + ) -> None: ... + +class SearchSortedOptions(FunctionOptions): + def __init__(self, side: _Side = "left") -> None: ... + +class SortOptions(FunctionOptions): + def __init__( + self, + sort_keys: Sequence[_SortKey] = (), + *, + null_placement: NullPlacement | None = None, + ) -> None: ... + +class SelectKOptions(FunctionOptions): + def __init__(self, k: int, sort_keys: Sequence[_SortKey]) -> None: ... + +class QuantileOptions(FunctionOptions): + def __init__( + self, + q: float | Sequence[float] = 0.5, + *, + interpolation: _Interpolation = "linear", + skip_nulls: bool = True, + min_count: int = 0, + ) -> 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 Utf8NormalizeOptions(FunctionOptions): + def __init__(self, form: _Form) -> 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: _Tiebreaker = "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: _UnexpectedKeyBehavior = "ignore", + ) -> None: ... + +# ==================== Expression ==================== + +class _SubstraitMessage(Protocol): + def SerializeToString(self) -> bytes: ... + +class Expression(_Weakrefable): + __hash__: ClassVar[None] # type: ignore[assignment] + + @staticmethod + def from_substrait( + message: bytes | memoryview | Buffer | _SubstraitMessage, + ) -> Expression: ... + def to_substrait( + self, schema: Schema, allow_arrow_extensions: bool = False + ) -> memoryview: ... + 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: ... + +# ==================== 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: dict[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: dict[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: dict[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: dict[str, DataType | str], + out_type: Schema | 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/_stubs_typing.pyi b/python/pyarrow-stubs/_stubs_typing.pyi index 90a79999511..a3cee2d5ffc 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 new file mode 100644 index 00000000000..79a92a48eb9 --- /dev/null +++ b/python/pyarrow-stubs/compute.pyi @@ -0,0 +1,1695 @@ +# 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, Sequence +from typing import Any, ParamSpec, TypeAlias, TypeVar + +import numpy as np +from numpy.typing import NDArray + +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, + _Form, + _Interpolation, + _NullHandling, + _Occurrence, + _RoundMode, + _Side, + _SortKey, + _Tiebreaker, + _TimezoneResolution, + _UnexpectedKeyBehavior, +) +from pyarrow._stubs_typing import ( + Indices, + Mask, + NullEncoding, + NullPlacement, + NullSelectionBehavior, + NumericLiteral, + Order, + TemporalLiteral, + TimeUnit, +) +from pyarrow.lib import ( + Array, + BaseListArray, + BinaryArray, + BinaryScalar, + BinaryViewArray, + BinaryViewScalar, + BooleanArray, + BooleanScalar, + ChunkedArray, + DataType, + Date32Array, + Date32Scalar, + Date64Array, + Date64Scalar, + DayTimeIntervalArray, + DayTimeIntervalScalar, + 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, + MonthIntervalArray, + MonthIntervalScalar, + 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") +_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. +_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 +) +_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. +_ArrayOrChunkedArray: TypeAlias = Array | ChunkedArray +_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 +_Literal: TypeAlias = NumericLiteral | TemporalLiteral | bool | str | bytes +_DecimalArray: TypeAlias = ( + Decimal32Array | Decimal64Array | Decimal128Array | Decimal256Array +) +# NumericArray includes the date, time, timestamp and duration arrays. +_NumericArray: TypeAlias = NumericArray | _DecimalArray +_NumericOrDurationArray: TypeAlias = _NumericArray +_NumericOrTemporalArray: TypeAlias = _NumericArray | MonthDayNanoIntervalArray +_StringArray: TypeAlias = StringArray | LargeStringArray | StringViewArray +_BinaryArray: TypeAlias = ( + BinaryArray | LargeBinaryArray | BinaryViewArray | FixedSizeBinaryArray +) +_StringOrBinaryArray: TypeAlias = _StringArray | _BinaryArray +_TemporalArray: TypeAlias = ( + Date32Array + | Date64Array + | Time32Array + | Time64Array + | TimestampArray + | DurationArray + | MonthDayNanoIntervalArray +) + +# =============================== Aggregations ======================================== +def all( + array: _ScalarOrArray, + /, + *, + skip_nulls: bool = True, + min_count: int = 1, + options: ScalarAggregateOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> BooleanScalar: ... + +any = _clone_signature(all) + +def approximate_median( + array: _ScalarOrArray, + /, + *, + skip_nulls: bool = True, + min_count: int = 1, + options: ScalarAggregateOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> DoubleScalar: ... +def count( + array: _ScalarOrArray, + /, + mode: _CountMode = "only_valid", + *, + options: CountOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> Int64Scalar: ... +def count_distinct( + array: _ScalarOrArray, + /, + mode: _CountMode = "only_valid", + *, + options: CountOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> Int64Scalar: ... +def first( + array: _ScalarOrArray, + /, + *, + skip_nulls: bool = True, + min_count: int = 1, + options: ScalarAggregateOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> Scalar: ... +def first_last( + array: _ScalarOrArray | _ArrayLike, + /, + *, + skip_nulls: bool = True, + min_count: int = 1, + options: ScalarAggregateOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> StructScalar: ... +def index( + data: _ArrayOrChunkedArray, + value: Scalar | _Literal, + start: int | None = None, + end: int | None = None, + *, + memory_pool: MemoryPool | None = None, +) -> Int64Scalar: ... +def kurtosis( + array: _ScalarOrArray | _ArrayLike, + /, + *, + skip_nulls: bool = True, + biased: bool = True, + min_count: int = 0, + options: SkewOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> DoubleScalar: ... + +last = _clone_signature(first) +max = _clone_signature(first) + +def mean( + array: _ScalarOrArray, + /, + *, + skip_nulls: bool = True, + min_count: int = 1, + options: ScalarAggregateOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> DoubleScalar | _DecimalScalar: ... + +min = _clone_signature(first) +min_max = _clone_signature(first_last) + +def mode( + array: _ScalarOrArray, + /, + n: int = 1, + *, + skip_nulls: bool = True, + min_count: int = 0, + options: ModeOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> StructArray: ... +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: _ScalarOrArray, + /, + *, + skip_nulls: bool = True, + min_count: int = 1, + options: ScalarAggregateOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _NumericScalar: ... +def quantile( + array: _ScalarOrArray, + /, + q: float | Sequence[float] = 0.5, + *, + interpolation: _Interpolation = "linear", + skip_nulls: bool = True, + min_count: int = 0, + options: QuantileOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> NumericArray | _DecimalArray: ... +def skew( + array: _ScalarOrArray | _ArrayLike, + /, + *, + skip_nulls: bool = True, + biased: bool = True, + min_count: int = 0, + options: SkewOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> DoubleScalar: ... +def stddev( + array: _ScalarOrArray, + /, + *, + ddof: float = 0, + skip_nulls: bool = True, + min_count: int = 0, + options: VarianceOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> DoubleScalar: ... +def sum( + array: _ScalarOrArray, + /, + *, + skip_nulls: bool = True, + min_count: int = 1, + options: ScalarAggregateOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _NumericScalar: ... +def tdigest( + array: _ScalarOrArray, + /, + 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: ... +def variance( + array: _ScalarOrArray | _ArrayLike, + /, + *, + ddof: int = 0, + skip_nulls: bool = True, + min_count: int = 0, + options: VarianceOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> DoubleScalar: ... + +# =============================== Element-wise ("scalar") functions =================== + +# ========================= Arithmetic functions ========================= +def abs( + x: _ComputeInput | NumericLiteral | TemporalLiteral, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _NumericOrDurationScalar | _NumericOrDurationArray | ChunkedArray | Expression: ... + +abs_checked = _clone_signature(abs) + +def add( + x: _ComputeInput | NumericLiteral | TemporalLiteral, + y: _ComputeInput | NumericLiteral | TemporalLiteral, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _NumericOrTemporalScalar | _NumericOrTemporalArray | ChunkedArray | Expression: ... + +add_checked = _clone_signature(add) + +def divide( + x: _ComputeInput | NumericLiteral | TemporalLiteral, + y: _ComputeInput | NumericLiteral | TemporalLiteral, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _NumericOrTemporalScalar | _NumericOrTemporalArray | ChunkedArray | Expression: ... + +divide_checked = _clone_signature(divide) + +def exp( + exponent: _ComputeInput | NumericLiteral, + /, + *, + memory_pool: MemoryPool | None = None, +) -> FloatingPointArray | _FloatScalar | ChunkedArray | Expression: ... + +expm1 = _clone_signature(exp) + +def hypot( + x: _ComputeInput | NumericLiteral, + y: _ComputeInput | NumericLiteral, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _FloatScalar | FloatingPointArray | ChunkedArray | Expression: ... +def modulo( + dividend: _ComputeInput | NumericLiteral, + divisor: _ComputeInput | NumericLiteral, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _NumericScalar | _NumericArray | ChunkedArray | Expression: ... + +modulo_checked = _clone_signature(modulo) +multiply = _clone_signature(add) +multiply_checked = _clone_signature(add) + +def negate( + x: _ComputeInput | NumericLiteral | TemporalLiteral, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _NumericOrDurationScalar | _NumericOrDurationArray | ChunkedArray | Expression: ... + +negate_checked = _clone_signature(negate) + +def power( + base: _ComputeInput | NumericLiteral, + exponent: _ComputeInput | NumericLiteral, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _NumericScalar | _NumericArray | ChunkedArray | Expression: ... + +power_checked = _clone_signature(power) +remainder = _clone_signature(modulo) +remainder_checked = _clone_signature(modulo) + +def sign( + x: _ComputeInput | NumericLiteral | TemporalLiteral, + /, + *, + memory_pool: MemoryPool | None = None, +) -> Int8Scalar | _FloatScalar | NumericArray | ChunkedArray | Expression: ... +def sqrt( + x: _ComputeInput | NumericLiteral, + /, + *, + memory_pool: MemoryPool | None = None, +) -> FloatingPointArray | _FloatScalar | ChunkedArray | Expression: ... + +sqrt_checked = _clone_signature(sqrt) +subtract = _clone_signature(add) +subtract_checked = _clone_signature(add) + +# ========================= Bit-wise functions ========================= +def bit_wise_and( + x: _ComputeInput | int, + y: _ComputeInput | int, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _NumericScalar | _NumericArray | ChunkedArray | Expression: ... +def bit_wise_not( + x: _ComputeInput | int, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _NumericScalar | _NumericArray | ChunkedArray | 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) + +# ========================= Rounding functions ========================= +def ceil( + x: _ComputeInput | NumericLiteral, + /, + *, + memory_pool: MemoryPool | None = None, +) -> ( + _FloatScalar + | _DecimalScalar + | FloatingPointArray + | _DecimalArray + | ChunkedArray + | Expression +): ... + +floor = _clone_signature(ceil) + +def round( + x: _ComputeInput | NumericLiteral, + /, + ndigits: int = 0, + round_mode: _RoundMode = "half_to_even", + *, + options: RoundOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _NumericScalar | _NumericArray | ChunkedArray | Expression: ... +def round_to_multiple( + x: _ComputeInput | NumericLiteral, + /, + multiple: float | Scalar = 1.0, + round_mode: _RoundMode = "half_to_even", + *, + options: RoundToMultipleOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _NumericScalar | _NumericArray | ChunkedArray | Expression: ... +def round_binary( + x: _ComputeInput | NumericLiteral, + s: _ComputeInput | int, + /, + round_mode: _RoundMode = "half_to_even", + *, + options: RoundBinaryOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _NumericScalar | _NumericArray | ChunkedArray | Expression: ... + +trunc = _clone_signature(ceil) + +# ========================= Logarithmic functions ========================= +def ln( + x: _ComputeInput | NumericLiteral, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _FloatScalar | FloatingPointArray | ChunkedArray | 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: _ComputeInput | NumericLiteral, + b: _ComputeInput | NumericLiteral, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _FloatScalar | FloatingPointArray | ChunkedArray | Expression: ... + +logb_checked = _clone_signature(logb) + +# ========================= Trigonometric functions ========================= +acos = _clone_signature(ln) +acos_checked = _clone_signature(ln) +asin = _clone_signature(ln) +asin_checked = _clone_signature(ln) +atan = _clone_signature(ln) + +def atan2( + y: _ComputeInput | NumericLiteral, + x: _ComputeInput | NumericLiteral, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _FloatScalar | FloatingPointArray | ChunkedArray | 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 = _clone_signature(ln) +atanh_checked = _clone_signature(ln) +cosh = _clone_signature(ln) +sinh = _clone_signature(ln) +tanh = _clone_signature(ln) + +# ========================= Comparisons ========================= +def equal( + x: _ComputeInput | _Literal, + y: _ComputeInput | _Literal, + /, + *, + memory_pool: MemoryPool | None = None, +) -> BooleanScalar | BooleanArray | ChunkedArray | 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: _ComputeInput | _Literal, + skip_nulls: bool = True, + options: ElementWiseAggregateOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> ( + _NumericOrTemporalScalar + | _StringOrBinaryScalar + | _NumericOrTemporalArray + | _StringOrBinaryArray + | ChunkedArray + | Expression +): ... + +min_element_wise = _clone_signature(max_element_wise) + +# ========================= Logical functions ========================= +def and_( + x: _ComputeInput | bool, + y: _ComputeInput | bool, + /, + *, + memory_pool: MemoryPool | None = None, +) -> BooleanScalar | BooleanArray | ChunkedArray | Expression: ... + +and_kleene = _clone_signature(and_) +and_not = _clone_signature(and_) +and_not_kleene = _clone_signature(and_) + +def invert( + x: _ComputeInput | bool, + /, + *, + memory_pool: MemoryPool | None = None, +) -> BooleanScalar | BooleanArray | ChunkedArray | Expression: ... + +or_ = _clone_signature(and_) +or_kleene = _clone_signature(and_) +xor = _clone_signature(and_) + +# ========================= String predicates ========================= +def ascii_is_alnum( + strings: _ComputeInput | str, + /, + *, + memory_pool: MemoryPool | None = None, +) -> BooleanScalar | BooleanArray | ChunkedArray | 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) + +# ========================= String transforms ========================= +def ascii_capitalize( + strings: _ComputeInput | str, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _StringScalar | _StringArray | ChunkedArray | 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: _ComputeInput | str | bytes, + /, + *, + memory_pool: MemoryPool | None = None, +) -> ( + Int32Scalar | Int64Scalar | Int32Array | Int64Array | ChunkedArray | Expression +): ... +def binary_repeat( + strings: _ComputeInput | str | bytes, + num_repeats: _ComputeInput | int, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _StringOrBinaryScalar | _StringOrBinaryArray | ChunkedArray | Expression: ... +def binary_replace_slice( + strings: _ComputeInput | str | bytes, + /, + start: int, + stop: int, + replacement: str | bytes, + *, + options: ReplaceSliceOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _StringOrBinaryScalar | _StringOrBinaryArray | ChunkedArray | Expression: ... +def binary_reverse( + strings: _ComputeInput | bytes, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _BinaryScalar | _BinaryArray | ChunkedArray | Expression: ... +def replace_substring( + strings: _ComputeInput | str | bytes, + /, + pattern: str | bytes, + replacement: str | bytes, + *, + max_replacements: int | None = None, + options: ReplaceSubstringOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _StringOrBinaryScalar | _StringOrBinaryArray | ChunkedArray | Expression: ... + +replace_substring_regex = _clone_signature(replace_substring) + +def utf8_capitalize( + strings: _ComputeInput | str, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _StringScalar | _StringArray | ChunkedArray | Expression: ... +def utf8_length( + strings: _ComputeInput | str, + /, + *, + memory_pool: MemoryPool | None = None, +) -> ( + Int32Scalar | Int64Scalar | Int32Array | Int64Array | ChunkedArray | Expression +): ... + +utf8_lower = _clone_signature(utf8_capitalize) + +def utf8_replace_slice( + strings: _ComputeInput | str, + /, + start: int, + stop: int, + replacement: str | bytes, + *, + options: ReplaceSliceOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _StringScalar | _StringArray | ChunkedArray | 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) + +def utf8_normalize( + strings: _ComputeInput | str, + /, + form: _Form, + *, + options: Utf8NormalizeOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _StringScalar | _StringArray | ChunkedArray | Expression: ... + +# ========================= String padding ========================= +def ascii_center( + strings: _ComputeInput | str, + /, + width: int, + padding: str = " ", + lean_left_on_odd_padding: bool = True, + *, + options: PadOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _StringScalar | _StringArray | ChunkedArray | 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: _ComputeInput | str, + /, + width: int, + padding: str = "0", + *, + options: ZeroFillOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _StringScalar | _StringArray | ChunkedArray | Expression: ... + +utf8_zfill = utf8_zero_fill + +# ========================= String trimming ========================= +def ascii_ltrim( + strings: _ComputeInput | str, + /, + characters: str | bytes, + *, + options: TrimOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _StringScalar | _StringArray | ChunkedArray | Expression: ... +def ascii_ltrim_whitespace( + strings: _ComputeInput | str, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _StringScalar | _StringArray | ChunkedArray | 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: _ComputeInput | str | bytes, + /, + *, + max_splits: int | None = None, + reverse: bool = False, + options: SplitOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _ListScalar | BaseListArray | ChunkedArray | Expression: ... +def split_pattern( + strings: _ComputeInput | str, + /, + pattern: str | bytes, + *, + max_splits: int | None = None, + reverse: bool = False, + options: SplitPatternOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _ListScalar | BaseListArray | ChunkedArray | Expression: ... + +split_pattern_regex = _clone_signature(split_pattern) +utf8_split_whitespace = _clone_signature(ascii_split_whitespace) + +# ========================= String component extraction ========================= +def extract_regex( + strings: _ComputeInput | str | bytes, + /, + pattern: str | bytes, + *, + options: ExtractRegexOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> StructScalar | StructArray | ChunkedArray | Expression: ... +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( + strings: _ComputeInput, + separator: _ComputeInput | str | bytes, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _StringOrBinaryScalar | _StringOrBinaryArray | ChunkedArray | Expression: ... +def binary_join_element_wise( + *strings: _ComputeInput | str | bytes, + null_handling: _NullHandling = "emit_null", + null_replacement: str = "", + options: JoinOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _StringOrBinaryScalar | _StringOrBinaryArray | ChunkedArray | Expression: ... + +# ========================= String Slicing ========================= +def binary_slice( + strings: _ComputeInput | bytes, + /, + start: int, + stop: int | None = None, + step: int = 1, + *, + options: SliceOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _BinaryScalar | _BinaryArray | ChunkedArray | Expression: ... +def utf8_slice_codeunits( + strings: _ComputeInput | str, + /, + start: int, + stop: int | None = None, + step: int = 1, + *, + options: SliceOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _StringScalar | _StringArray | ChunkedArray | Expression: ... + +# ========================= Containment tests ========================= +def count_substring( + strings: _ComputeInput | str | bytes, + /, + pattern: str | bytes, + *, + 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: _ComputeInput | str | bytes, + /, + pattern: str | bytes, + *, + ignore_case: bool = False, + options: MatchSubstringOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> BooleanScalar | BooleanArray | ChunkedArray | Expression: ... + +find_substring = _clone_signature(count_substring) +find_substring_regex = _clone_signature(count_substring) + +def index_in( + values: _ComputeInput | _Literal, + /, + value_set: _ArrayOrChunkedArray, + *, + skip_nulls: bool = False, + options: SetLookupOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> Int32Scalar | Int32Array | ChunkedArray | Expression: ... +def is_in( + values: _ComputeInput | _Literal, + /, + value_set: _ArrayOrChunkedArray, + *, + skip_nulls: bool = False, + options: SetLookupOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> BooleanScalar | BooleanArray | ChunkedArray | Expression: ... + +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) + +def index_in_meta_binary( + values: _ArrayOrChunkedArray | _ArrayLike, + value_set: _ArrayOrChunkedArray | _ArrayLike, + /, + *, + memory_pool: MemoryPool | None = None, +) -> Int32Scalar | Int32Array | ChunkedArray: ... +def is_in_meta_binary( + values: _ArrayOrChunkedArray | _ArrayLike, + value_set: _ArrayOrChunkedArray | _ArrayLike, + /, + *, + memory_pool: MemoryPool | None = None, +) -> BooleanScalar | BooleanArray | ChunkedArray: ... + +# ========================= Categorizations ========================= +def is_finite( + values: _ComputeInput | NumericLiteral, + /, + *, + memory_pool: MemoryPool | None = None, +) -> BooleanScalar | BooleanArray | ChunkedArray | Expression: ... + +is_inf = _clone_signature(is_finite) +is_nan = _clone_signature(is_finite) + +def is_null( + values: _ComputeInput | _Literal, + /, + *, + nan_is_null: bool = False, + options: NullOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> BooleanScalar | BooleanArray | ChunkedArray | Expression: ... +def is_valid( + values: _ComputeInput | _Literal, + /, + *, + memory_pool: MemoryPool | None = None, +) -> BooleanScalar | BooleanArray | ChunkedArray | Expression: ... + +true_unless_null = _clone_signature(is_valid) + +# ========================= Selecting / multiplexing ========================= +def case_when( + cond: _ComputeInput, + /, + *cases: _ComputeInput | _Literal, + memory_pool: MemoryPool | None = None, +) -> _ScalarOrArray | Expression: ... +def choose( + indices: _ComputeInput | int, + /, + *values: _ComputeInput | _Literal, + memory_pool: MemoryPool | None = None, +) -> _ScalarOrArray | Expression: ... +def coalesce( + *values: _ComputeInput | _Literal, memory_pool: MemoryPool | None = None +) -> _ScalarOrArray | Expression: ... +def if_else( + cond: _ComputeInput | bool | np.generic, + left: _ComputeInput | _Literal, + right: _ComputeInput | _Literal, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _ScalarOrArray | Expression: ... +def fill_null( + values: _ScalarOrArray, + fill_value: _ScalarOrArray | _Literal, +) -> _ScalarOrArray: ... + +# ========================= Structural transforms ========================= +def list_value_length( + lists: _ComputeInput, + /, + *, + memory_pool: MemoryPool | None = None, +) -> ( + Int32Scalar | Int64Scalar | Int32Array | Int64Array | ChunkedArray | Expression +): ... +def make_struct( + *args: _ComputeInput | _Literal, + field_names: Sequence[str] = (), + 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: ... + +# ========================= Conversions ========================= +def ceil_temporal( + timestamps: _ComputeInput | TemporalLiteral, + /, + 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 | ChunkedArray | Expression: ... + +floor_temporal = _clone_signature(ceil_temporal) +round_temporal = _clone_signature(ceil_temporal) + +def cast( + 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: ... +def strftime( + timestamps: _ComputeInput | TemporalLiteral, + /, + 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: _ComputeInput | str, + /, + format: str | bytes, + unit: TimeUnit, + error_is_null: bool = False, + *, + options: StrptimeOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> TimestampScalar | TimestampArray | ChunkedArray | Expression: ... +def run_end_encode( + array: _ArrayOrChunkedArray | _ArrayLike, + /, + run_end_type: DataType | str = ..., + *, + options: RunEndEncodeOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> RunEndEncodedArray | ChunkedArray: ... +def run_end_decode( + array: _ArrayOrChunkedArray | _ArrayLike, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _ArrayOrChunkedArray: ... + +# ========================= Temporal component extraction ========================= +def day( + values: _ComputeInput | TemporalLiteral, + /, + *, + memory_pool: MemoryPool | None = None, +) -> Int64Scalar | Int64Array | ChunkedArray | Expression: ... +def day_of_week( + values: _ComputeInput | TemporalLiteral, + /, + *, + 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: _ComputeInput | TemporalLiteral, + /, + *, + memory_pool: MemoryPool | None = None, +) -> Int64Scalar | Int64Array | ChunkedArray | Expression: ... +def is_dst( + values: _ComputeInput | TemporalLiteral, + /, + *, + memory_pool: MemoryPool | None = None, +) -> BooleanScalar | BooleanArray | ChunkedArray | Expression: ... +def iso_week( + values: _ComputeInput | TemporalLiteral, + /, + *, + memory_pool: MemoryPool | None = None, +) -> Int64Scalar | Int64Array | ChunkedArray | Expression: ... + +iso_year = _clone_signature(iso_week) + +def is_leap_year( + values: _ComputeInput | TemporalLiteral, + /, + *, + memory_pool: MemoryPool | None = None, +) -> BooleanScalar | BooleanArray | ChunkedArray | 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) + +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) + +def week( + values: _ComputeInput | TemporalLiteral, + /, + *, + 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: ... + +year = _clone_signature(iso_week) + +def year_month_day( + values: _ComputeInput | TemporalLiteral, + /, + *, + memory_pool: MemoryPool | None = None, +) -> StructScalar | StructArray | ChunkedArray | Expression: ... + +iso_calendar = _clone_signature(year_month_day) + +# ========================= Temporal difference ========================= +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, + /, + *, + 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: _ComputeInput | TemporalLiteral, + end: _ComputeInput | TemporalLiteral, + /, + *, + memory_pool: MemoryPool | None = None, +) -> ( + MonthDayNanoIntervalScalar | MonthDayNanoIntervalArray | ChunkedArray | 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) +seconds_between = _clone_signature(days_between) + +def weeks_between( + start: _ComputeInput | TemporalLiteral, + end: _ComputeInput | TemporalLiteral, + /, + *, + 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) + +# ========================= Timezone handling ========================= +def assume_timezone( + timestamps: _ComputeInput | TemporalLiteral, + /, + timezone: str | bytes, + *, + ambiguous: _TimezoneResolution = "raise", + nonexistent: _TimezoneResolution = "raise", + options: AssumeTimezoneOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> TimestampScalar | TimestampArray | ChunkedArray | Expression: ... +def local_timestamp( + values: _ComputeInput | TemporalLiteral, + /, + *, + memory_pool: MemoryPool | None = None, +) -> TimestampScalar | TimestampArray | ChunkedArray | Expression: ... + +# ========================= Random number generation ========================= +def random( + n: int, + *, + initializer: Hashable = "system", + options: RandomOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> DoubleArray: ... + +# =============================== Array-wise ("vector") functions ===================== + +# ========================= Cumulative Functions ========================= +def cumulative_sum( + values: _ArrayOrChunkedArray | _ArrayLike, + /, + start: float | Scalar | None = None, + *, + skip_nulls: bool = False, + options: CumulativeOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _NumericArray | ChunkedArray: ... + +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) + +# ========================= Statistical functions ========================= +def winsorize( + array: _ScalarOrArray | _ArrayLike, + /, + lower_limit: float, + upper_limit: float, + *, + options: WinsorizeOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _NumericArray | ChunkedArray: ... + +# ========================= Associative transforms ========================= +def dictionary_encode( + array: _ScalarOrArray | _ArrayLike, + /, + null_encoding: NullEncoding = "mask", + *, + options: DictionaryEncodeOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> DictionaryArray | ChunkedArray: ... +def unique( + array: _ScalarOrArray | _ArrayLike, + /, + *, + memory_pool: MemoryPool | None = None, +) -> Array: ... +def value_counts( + array: _ScalarOrArray | _ArrayLike, + /, + *, + memory_pool: MemoryPool | None = None, +) -> StructArray: ... +def dictionary_decode( + dictionary_array: _ArrayOrChunkedArray, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _ArrayOrChunkedArray: ... + +# ========================= Selections ========================= +def array_filter( + array: _ArrayOrChunkedArray | _ArrayLike, + selection_filter: Mask, + /, + null_selection_behavior: NullSelectionBehavior = "drop", + *, + options: FilterOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _ArrayOrChunkedArray: ... +def array_take( + array: _ArrayOrChunkedArray | _ArrayLike, + indices: Indices, + /, + *, + boundscheck: bool = True, + options: TakeOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _ArrayOrChunkedArray: ... +def drop_null( + input: _ArrayOrChunkedArray | _ArrayLike | RecordBatch | Table, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _ArrayOrChunkedArray | RecordBatch | Table: ... +def filter( + 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: ... +def inverse_permutation( + indices: _ArrayOrChunkedArray | _ArrayLike, + /, + max_index: int = -1, + output_type: DataType | str | None = None, + *, + options: InversePermutationOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> IntegerArray | ChunkedArray: ... +def scatter( + values: _ArrayOrChunkedArray | _ArrayLike, + indices: _ArrayOrChunkedArray | _ArrayLike, + /, + max_index: int = -1, + *, + options: ScatterOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _ArrayOrChunkedArray: ... +def take( + data: _ArrayOrChunkedArray | _ArrayLike | RecordBatch | Table, + indices: Indices, + *, + boundscheck: bool = True, + memory_pool: MemoryPool | None = None, +) -> _ArrayOrChunkedArray | RecordBatch | Table: ... + +# ========================= Containment tests ========================= +def indices_nonzero( + values: _ArrayOrChunkedArray | _ArrayLike | int, + /, + *, + memory_pool: MemoryPool | None = None, +) -> UInt64Array: ... + +# ========================= Sorts and partitions ========================= +def array_sort_indices( + array: _ArrayOrChunkedArray | _ArrayLike, + /, + order: Order = "ascending", + *, + null_placement: NullPlacement = "at_end", + options: ArraySortOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> UInt64Array | ChunkedArray: ... +def partition_nth_indices( + array: Array | _ArrayLike, + /, + pivot: int, + *, + null_placement: NullPlacement = "at_end", + options: PartitionNthOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> UInt64Array: ... +def rank( + input: _ArrayOrChunkedArray | _ArrayLike, + /, + sort_keys: Order | Sequence[_SortKey] = "ascending", + *, + null_placement: NullPlacement | None = None, + tiebreaker: _Tiebreaker = "first", + options: RankOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> UInt64Array: ... +def rank_normal( + input: _ArrayOrChunkedArray | _ArrayLike, + /, + sort_keys: Order | Sequence[_SortKey] = "ascending", + *, + null_placement: NullPlacement | None = None, + options: RankQuantileOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> DoubleArray: ... +def rank_quantile( + input: _ArrayOrChunkedArray | _ArrayLike, + /, + 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 | _ArrayLike | RecordBatch | Table, + /, + k: int, + sort_keys: Sequence[_SortKey], + *, + options: SelectKOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> UInt64Array: ... +def sort_indices( + input: _ArrayOrChunkedArray | _ArrayLike | RecordBatch | Table, + /, + sort_keys: Sequence[_SortKey] = (), + *, + null_placement: NullPlacement | None = None, + options: SortOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> UInt64Array: ... +def search_sorted( + values: _ArrayOrChunkedArray | _ArrayLike, + needles: _ScalarOrArray | _ArrayLike | _Literal, + /, + side: _Side = "left", + *, + options: SearchSortedOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> UInt64Scalar | UInt64Array: ... +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: ... + +# ========================= Structural transforms ========================= +def list_contains( + lists: _ComputeInput, + value: _ComputeInput | _Literal, + /, + *, + memory_pool: MemoryPool | None = None, +) -> BooleanScalar | BooleanArray | ChunkedArray | Expression: ... +def list_element( + lists: _ComputeInput, + index: _ComputeInput | int, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _ScalarOrArray | Expression: ... +def list_flatten( + lists: _ScalarOrArray | _ArrayLike, + /, + recursive: bool = False, + *, + options: ListFlattenOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _ArrayOrChunkedArray: ... +def list_parent_indices( + lists: _ArrayOrChunkedArray | _ArrayLike, + /, + *, + memory_pool: MemoryPool | None = None, +) -> Int64Array | ChunkedArray: ... +def list_slice( + lists: _ComputeInput, + /, + 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, +) -> _ListScalar | BaseListArray | ChunkedArray | Expression: ... +def map_lookup( + container: _ScalarOrArray | Expression, + /, + query_key: Scalar | _Literal, + occurrence: _Occurrence, + *, + options: MapLookupOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _ScalarOrArray | Expression: ... +def struct_field( + values: _ScalarOrArray | Expression, + /, + indices: Sequence[str | bytes | int] | bytes | str | int | Expression, + *, + options: StructFieldOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _ScalarOrArray | Expression: ... + +# ========================= Replace functions ========================= +def fill_null_backward( + values: _ArrayOrChunkedArray | _ArrayLike, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _ArrayOrChunkedArray: ... +def fill_null_forward( + values: _ArrayOrChunkedArray | _ArrayLike, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _ArrayOrChunkedArray: ... +def replace_with_mask( + values: _ArrayOrChunkedArray | _ArrayLike, + mask: Mask, + replacements: _ScalarOrArray | _ArrayLike, + /, + *, + memory_pool: MemoryPool | None = None, +) -> _ArrayOrChunkedArray: ... + +# ========================= Pairwise functions ========================= +def pairwise_diff( + input: Array | _ArrayLike, + /, + period: int = 1, + *, + options: PairwiseOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> _NumericOrTemporalArray: ... + +pairwise_diff_checked = _clone_signature(pairwise_diff) diff --git a/python/pyarrow/_compute.pyx b/python/pyarrow/_compute.pyx index 789e710875e..d3eeb0688a5 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 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 @@ -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 d9359c8e77d..cd0d011caef 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: diff --git a/python/pyproject.toml b/python/pyproject.toml index 1556354f6bd..a035c65a278 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]]