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_io_formats.py b/python/pyarrow-stubs-tests/test_io_formats.py new file mode 100644 index 00000000000..9d9eb034966 --- /dev/null +++ b/python/pyarrow-stubs-tests/test_io_formats.py @@ -0,0 +1,181 @@ +# 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 io +from typing import TYPE_CHECKING + +import pyarrow as pa +import pyarrow.csv as csv +import pyarrow.feather as feather +import pyarrow.ipc as ipc +import pyarrow.json as pa_json + +from _check import assert_type, check + + +def test_io_buffers_and_streams() -> None: + buf = pa.allocate_buffer(8) + check(assert_type(buf, pa.Buffer), pa.Buffer) + check(assert_type(buf.size, int), int) + check(assert_type(buf.to_pybytes(), bytes), bytes) + check(assert_type(buf.slice(0, 4), pa.Buffer), pa.Buffer) + + rbuf = pa.allocate_buffer(8, resizable=True) + check(assert_type(rbuf, pa.ResizableBuffer), pa.ResizableBuffer) + rbuf.resize(16) + check(assert_type(buf.equals(rbuf), bool), bool) + + check(assert_type(pa.allocate_buffer(8, None, True), pa.ResizableBuffer), + pa.ResizableBuffer) + + src = pa.py_buffer(b"abc") + fbuf = pa.foreign_buffer(src.address, src.size, base=src) + check(assert_type(fbuf, pa.Buffer), pa.Buffer) + + sink = pa.BufferOutputStream() + sink.write(b"hello") + out = sink.getvalue() + check(assert_type(out, pa.Buffer), pa.Buffer) + + reader = pa.BufferReader(out) + check(assert_type(reader.read(), bytes), bytes) + + cache_options = pa.CacheOptions(lazy=None, prefetch_limit=None) + check(assert_type(cache_options, pa.CacheOptions), pa.CacheOptions) + check(assert_type(cache_options.lazy, bool), bool) + check(assert_type(cache_options.prefetch_limit, int), int) + check( + assert_type(pa.CacheOptions.from_network_metrics(100, 50), + pa.CacheOptions), + pa.CacheOptions, + ) + + check(assert_type(pa.Codec.supports_compression_level("gzip"), bool), bool) + + compressed_buf = pa.compress(b"hello world", codec="gzip") + check(assert_type(compressed_buf, pa.Buffer), pa.Buffer) + compressed_bytes = pa.compress(b"hello world", codec="gzip", asbytes=True) + check(assert_type(compressed_bytes, bytes), bytes) + decompressed = pa.decompress( + compressed_bytes, decompressed_size=11, codec="gzip", asbytes=True + ) + check(assert_type(decompressed, bytes), bytes) + + +def test_buffer_protocol_inputs() -> None: + sink = pa.BufferOutputStream() + check(assert_type(sink.write(memoryview(b"ab")), int), int) + check(assert_type(sink.write(pa.py_buffer(b"cd")), int), int) + + reader = pa.BufferReader(b"hello world") + check(assert_type(reader.readinto(bytearray(2)), int), int) + check(assert_type(reader.readinto(memoryview(bytearray(2))), int), int) + check(assert_type(reader.readinto(pa.allocate_buffer(2)), int), int) + + sink = pa.BufferOutputStream() + assert_type(sink.writelines( + [b"ab", bytearray(b"cd"), memoryview(b"ef"), pa.py_buffer(b"gh")] + ), None) + assert sink.getvalue().to_pybytes() == b"abcdefgh" + + stream = pa.TransformInputStream( + pa.BufferReader(b"abc"), lambda buf: buf.to_pybytes().upper() + ) + check(assert_type(stream.read(), bytes), bytes) + + +class _BytesStream: + def __init__(self, data: bytes = b"") -> None: + self.data = data + + def read(self, size: int = -1, /) -> bytes: + data, self.data = self.data, b"" + return data + + def write(self, data: bytes, /) -> int: + self.data += data + return len(data) + + +def test_download_upload() -> None: + # File objects + dest = io.BytesIO() + assert_type(pa.BufferReader(b"abc").download(dest), None) + assert dest.getvalue() == b"abc" + assert_type(pa.BufferOutputStream().upload(io.BytesIO(b"abc")), None) + + # Other objects with read and write methods + stream = _BytesStream() + assert_type(pa.BufferReader(b"abc").download(stream), None) + assert stream.data == b"abc" + sink = pa.BufferOutputStream() + assert_type(sink.upload(_BytesStream(b"abc")), None) + assert sink.getvalue().to_pybytes() == b"abc" + + +def test_ipc() -> None: + batch = pa.record_batch([pa.array([1, 2])], names=["a"]) + sink = pa.BufferOutputStream() + opts = ipc.IpcWriteOptions(compression="zstd") + with ipc.new_stream(sink, batch.schema, options=opts) as writer: + writer.write_batch(batch) + buf = sink.getvalue() + + with ipc.open_stream(buf) as reader: + check(assert_type(reader.schema, pa.Schema), pa.Schema) + table = reader.read_all() + check(assert_type(table, pa.Table), pa.Table) + + +def test_csv_and_json() -> None: + read_opts = csv.ReadOptions(use_threads=False) + parse_opts = csv.ParseOptions(delimiter=",") + convert_opts = csv.ConvertOptions(check_utf8=True) + table = csv.read_csv( + pa.BufferReader(b"a,b\n1,2\n"), + read_options=read_opts, + parse_options=parse_opts, + convert_options=convert_opts, + ) + check(assert_type(table, pa.Table), pa.Table) + + jtable = pa_json.read_json(pa.BufferReader(b'{"a": 1}\n{"a": 2}\n')) + check(assert_type(jtable, pa.Table), pa.Table) + + +def test_feather() -> None: + table = pa.table({"a": [1, 2]}) + sink = pa.BufferOutputStream() + feather.write_feather(table, sink) + read_back = feather.read_table(pa.BufferReader(sink.getvalue())) + check(assert_type(read_back, pa.Table), pa.Table) + + +def test_invalid_usage() -> None: + if TYPE_CHECKING: + # str doesn't support the buffer protocol + pa.BufferOutputStream().write("text") # type: ignore[arg-type] + pa.BufferReader(b"abc").readinto("text") # type: ignore[arg-type] + pa.BufferOutputStream().writelines(["text"]) # type: ignore[list-item] + + def to_str(buf: pa.Buffer) -> str: + return "text" + + stream = pa.BufferReader(b"abc") + pa.TransformInputStream(stream, to_str) # type: ignore[arg-type] + pa.allocate_buffer("not an int") # type: ignore[call-overload] + pa.compress(b"abc", codec="invalid") # type: ignore[call-overload] # ty: ignore[no-matching-overload] # noqa: E501 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/__init__.pyi b/python/pyarrow-stubs/__init__.pyi index 5f34a72a63a..406efb33b0b 100644 --- a/python/pyarrow-stubs/__init__.pyi +++ b/python/pyarrow-stubs/__init__.pyi @@ -43,8 +43,17 @@ from pyarrow.lib import ( Bool8Type as Bool8Type, BooleanArray as BooleanArray, BooleanScalar as BooleanScalar, + Buffer as Buffer, + BufferOutputStream as BufferOutputStream, + BufferReader as BufferReader, + BufferedInputStream as BufferedInputStream, + BufferedOutputStream as BufferedOutputStream, BuildInfo as BuildInfo, + CacheOptions as CacheOptions, ChunkedArray as ChunkedArray, + Codec as Codec, + CompressedInputStream as CompressedInputStream, + CompressedOutputStream as CompressedOutputStream, CppBuildInfo as CppBuildInfo, DataType as DataType, Date32Array as Date32Array, @@ -88,6 +97,7 @@ from pyarrow.lib import ( FixedSizeBinaryArray as FixedSizeBinaryArray, FixedSizeBinaryScalar as FixedSizeBinaryScalar, FixedSizeBinaryType as FixedSizeBinaryType, + FixedSizeBufferWriter as FixedSizeBufferWriter, FixedSizeListArray as FixedSizeListArray, FixedSizeListScalar as FixedSizeListScalar, FixedSizeListType as FixedSizeListType, @@ -130,22 +140,29 @@ from pyarrow.lib import ( MapScalar as MapScalar, MapType as MapType, MemoryManager as MemoryManager, + MemoryMappedFile as MemoryMappedFile, MemoryPool as MemoryPool, Month as Month, + MockOutputStream as MockOutputStream, MonthDayNano as MonthDayNano, MonthDayNanoIntervalArray as MonthDayNanoIntervalArray, MonthDayNanoIntervalScalar as MonthDayNanoIntervalScalar, MonthIntervalArray as MonthIntervalArray, MonthIntervalScalar as MonthIntervalScalar, NA as NA, + NativeFile as NativeFile, NullArray as NullArray, NullScalar as NullScalar, NumericArray as NumericArray, + OSFile as OSFile, OpaqueArray as OpaqueArray, OpaqueScalar as OpaqueScalar, OpaqueType as OpaqueType, ProxyMemoryPool as ProxyMemoryPool, + PythonFile as PythonFile, RecordBatch as RecordBatch, + RecordBatchReader as RecordBatchReader, + ResizableBuffer as ResizableBuffer, RunEndEncodedArray as RunEndEncodedArray, RunEndEncodedScalar as RunEndEncodedScalar, RunEndEncodedType as RunEndEncodedType, @@ -176,6 +193,7 @@ from pyarrow.lib import ( TimestampArray as TimestampArray, TimestampScalar as TimestampScalar, TimestampType as TimestampType, + TransformInputStream as TransformInputStream, UInt16Array as UInt16Array, UInt16Scalar as UInt16Scalar, UInt32Array as UInt32Array, @@ -192,6 +210,7 @@ from pyarrow.lib import ( UuidScalar as UuidScalar, UuidType as UuidType, VersionInfo as VersionInfo, + allocate_buffer as allocate_buffer, array as array, binary as binary, binary_view as binary_view, @@ -199,12 +218,14 @@ from pyarrow.lib import ( bool_ as bool_, build_info as build_info, chunked_array as chunked_array, + compress as compress, concat_arrays as concat_arrays, concat_batches as concat_batches, concat_tables as concat_tables, cpp_build_info as cpp_build_info, cpp_version as cpp_version, cpp_version_info as cpp_version_info, + create_memory_map as create_memory_map, date32 as date32, date64 as date64, day_time_interval as day_time_interval, @@ -212,6 +233,7 @@ from pyarrow.lib import ( decimal256 as decimal256, decimal32 as decimal32, decimal64 as decimal64, + decompress as decompress, default_cpu_memory_manager as default_cpu_memory_manager, default_memory_pool as default_memory_pool, dense_union as dense_union, @@ -223,12 +245,15 @@ from pyarrow.lib import ( float16 as float16, float32 as float32, float64 as float64, + foreign_buffer as foreign_buffer, from_numpy_dtype as from_numpy_dtype, infer_type as infer_type, + input_stream as input_stream, int16 as int16, int32 as int32, int64 as int64, int8 as int8, + io_thread_count as io_thread_count, jemalloc_memory_pool as jemalloc_memory_pool, jemalloc_set_decay_ms as jemalloc_set_decay_ms, json_ as json_, @@ -242,13 +267,16 @@ from pyarrow.lib import ( log_memory_allocations as log_memory_allocations, logging_memory_pool as logging_memory_pool, map_ as map_, + memory_map as memory_map, mimalloc_memory_pool as mimalloc_memory_pool, month_day_nano_interval as month_day_nano_interval, month_interval as month_interval, null as null, nulls as nulls, opaque as opaque, + output_stream as output_stream, proxy_memory_pool as proxy_memory_pool, + py_buffer as py_buffer, record_batch as record_batch, register_extension_type as register_extension_type, repeat as repeat, @@ -256,6 +284,7 @@ from pyarrow.lib import ( runtime_info as runtime_info, scalar as scalar, schema as schema, + set_io_thread_count as set_io_thread_count, set_memory_pool as set_memory_pool, set_timezone_db_path as set_timezone_db_path, sparse_union as sparse_union, @@ -269,6 +298,7 @@ from pyarrow.lib import ( time64 as time64, timestamp as timestamp, total_allocated_bytes as total_allocated_bytes, + transcoding_input_stream as transcoding_input_stream, type_for_alias as type_for_alias, uint16 as uint16, uint32 as uint32, @@ -281,7 +311,19 @@ from pyarrow.lib import ( uuid as uuid, ) +from pyarrow import ipc as ipc from pyarrow import types as types +from pyarrow.ipc import ( + Message as Message, + MessageReader as MessageReader, + MetadataVersion as MetadataVersion, + RecordBatchFileReader as RecordBatchFileReader, + RecordBatchFileWriter as RecordBatchFileWriter, + RecordBatchStreamReader as RecordBatchStreamReader, + RecordBatchStreamWriter as RecordBatchStreamWriter, + deserialize_pandas as deserialize_pandas, + serialize_pandas as serialize_pandas, +) # pyarrow/__init__.py imports pyarrow.lib._NULL as NULL NULL: NullScalar diff --git a/python/pyarrow-stubs/__lib/array.pyi b/python/pyarrow-stubs/__lib/array.pyi index 87244f36419..11a2a8f99a6 100644 --- a/python/pyarrow-stubs/__lib/array.pyi +++ b/python/pyarrow-stubs/__lib/array.pyi @@ -207,9 +207,9 @@ class Array(_PandasConvertible[pd.Series]): def is_valid(self) -> BooleanArray: ... def fill_null(self, fill_value: Any) -> Self: ... @overload - def __getitem__(self, key: SupportsIndex) -> Scalar: ... + def __getitem__(self, key: SupportsIndex, /) -> Scalar: ... @overload - def __getitem__(self, key: builtins.slice) -> Self: ... + def __getitem__(self, key: builtins.slice, /) -> Self: ... def slice(self, offset: int = 0, length: int | None = None) -> Self: ... def take(self, indices: Indices) -> Self: ... def drop_null(self) -> Self: ... diff --git a/python/pyarrow-stubs/__lib/io.pyi b/python/pyarrow-stubs/__lib/io.pyi index 8a1da39a1cf..42edb0fe2dc 100644 --- a/python/pyarrow-stubs/__lib/io.pyi +++ b/python/pyarrow-stubs/__lib/io.pyi @@ -15,11 +15,380 @@ # specific language governing permissions and limitations # under the License. -# Placeholder stub - complete annotations in future PR. -# At runtime, these symbols are provided by the pyarrow.lib C extension. +import builtins +from collections.abc import Callable, Iterable +from io import IOBase +from typing import Any, Literal, Self, SupportsIndex, TypeAlias, overload -from typing import Any +from _typeshed import StrPath, SupportsRead +from pyarrow._stubs_typing import Compression, SupportPyBuffer, SupportsReadWrite +from pyarrow.lib import ( + Device, + DeviceAllocationType, + KeyValueMetadata, + MemoryManager, + MemoryPool, + _Weakrefable, +) -class Buffer: ... +def io_thread_count() -> int: ... +def set_io_thread_count(count: int) -> None: ... -def __getattr__(name: str) -> Any: ... +_Mode: TypeAlias = Literal["rb", "wb", "rb+", "ab"] + +class NativeFile(_Weakrefable): + _default_chunk_size: int + + def __enter__(self) -> Self: ... + def __exit__(self, exc_type: object, exc_value: object, tb: object) -> None: ... + @property + def mode(self) -> _Mode: ... + def readable(self) -> bool: ... + def writable(self) -> bool: ... + def seekable(self) -> bool: ... + def isatty(self) -> bool: ... + def fileno(self) -> int: ... + @property + def closed(self) -> bool: ... + def close(self) -> None: ... + def size(self) -> int: ... + def metadata(self) -> KeyValueMetadata: ... + def tell(self) -> int: ... + def seek(self, position: int, whence: int = 0) -> int: ... + def flush(self) -> None: ... + def write(self, data: bytes | SupportPyBuffer) -> int: ... + def read(self, nbytes: int | None = None) -> bytes: ... + def get_stream(self, file_offset: int, nbytes: int) -> NativeFile: ... + def read_at(self, nbytes: int, offset: int) -> bytes: ... + def read1(self, nbytes: int | None = None) -> bytes: ... + def readall(self) -> bytes: ... + def readinto(self, b: SupportPyBuffer) -> int: ... + def readline(self, size: int | None = None) -> bytes: ... + def readlines(self, hint: int | None = None) -> list[bytes]: ... + def __iter__(self) -> Self: ... + def __next__(self) -> bytes: ... + def read_buffer(self, nbytes: int | None = None) -> Buffer: ... + def truncate(self) -> None: ... + def writelines(self, lines: Iterable[bytes | SupportPyBuffer]) -> None: ... + def download( + self, + stream_or_path: StrPath | SupportsReadWrite, + buffer_size: int | None = None, + ) -> None: ... + def upload( + self, stream: SupportsRead[bytes], buffer_size: int | None = None + ) -> None: ... + +# ---------------------------------------------------------------------- +# Python file-like objects + +class PythonFile(NativeFile): + def __init__( + self, handle: IOBase, mode: Literal["r", "w"] | None = None + ) -> None: ... + def truncate(self, pos: int | None = None) -> None: ... + +class MemoryMappedFile(NativeFile): + @staticmethod + def create(path: str, size: int) -> MemoryMappedFile: ... + def resize(self, new_size: int) -> None: ... + +def memory_map( + path: str, mode: Literal["r", "rb", "w", "wb", "r+", "r+b", "rb+"] = "r" +) -> MemoryMappedFile: ... +def create_memory_map(path: str, size: int) -> MemoryMappedFile: ... + +class OSFile(NativeFile): + def __init__( + self, + path: str, + mode: Literal["r", "rb", "w", "wb", "a", "ab"], + memory_pool: MemoryPool | None = None, + ) -> None: ... + +class FixedSizeBufferWriter(NativeFile): + def __init__(self, buffer: Buffer) -> None: ... + def set_memcopy_threads(self, num_threads: int) -> None: ... + def set_memcopy_blocksize(self, blocksize: int) -> None: ... + def set_memcopy_threshold(self, threshold: int) -> None: ... + +# ---------------------------------------------------------------------- +# Arrow buffers + +class Buffer(_Weakrefable): + def __len__(self) -> int: ... + @property + def size(self) -> int: ... + @property + def address(self) -> int: ... + def hex(self) -> bytes: ... + @property + def is_mutable(self) -> bool: ... + @property + def is_cpu(self) -> bool: ... + @property + def device(self) -> Device: ... + @property + def memory_manager(self) -> MemoryManager: ... + @property + def device_type(self) -> DeviceAllocationType: ... + @property + def parent(self) -> Buffer | None: ... + @overload + def __getitem__(self, key: builtins.slice, /) -> Buffer: ... + @overload + def __getitem__(self, key: int, /) -> int: ... + def slice(self, offset: int = 0, length: int | None = None) -> Buffer: ... + def equals(self, other: Buffer) -> bool: ... + def __reduce_ex__(self, protocol: SupportsIndex, /) -> tuple[Any, ...]: ... + def to_pybytes(self) -> bytes: ... + def __buffer__(self, flags: int, /) -> memoryview: ... + +class ResizableBuffer(Buffer): + def resize(self, new_size: int, shrink_to_fit: bool = False) -> None: ... + +@overload +def allocate_buffer( + size: int, memory_pool: MemoryPool | None = None, *, resizable: Literal[True] +) -> ResizableBuffer: ... +@overload +def allocate_buffer( + size: int, memory_pool: MemoryPool | None, resizable: Literal[True] +) -> ResizableBuffer: ... +@overload +def allocate_buffer( + size: int, memory_pool: MemoryPool | None = None, resizable: bool = False +) -> Buffer: ... + +# ---------------------------------------------------------------------- +# Arrow Stream +class BufferOutputStream(NativeFile): + def __init__(self, memory_pool: MemoryPool | None = None) -> None: ... + def getvalue(self) -> Buffer: ... + +class MockOutputStream(NativeFile): ... + +class BufferReader(NativeFile): + def __init__(self, obj: Buffer | bytes | SupportPyBuffer) -> None: ... + +class CompressedInputStream(NativeFile): + def __init__( + self, + stream: StrPath | NativeFile | IOBase, + compression: Literal["bz2", "brotli", "gzip", "lz4", "zstd"], + ) -> None: ... + +class CompressedOutputStream(NativeFile): + def __init__( + self, + stream: StrPath | NativeFile | IOBase, + compression: Literal["bz2", "brotli", "gzip", "lz4", "zstd"], + ) -> None: ... + +class BufferedInputStream(NativeFile): + def __init__( + self, + stream: NativeFile, + buffer_size: int, + memory_pool: MemoryPool | None = None, + ) -> None: ... + def detach(self) -> NativeFile: ... + +class BufferedOutputStream(NativeFile): + def __init__( + self, + stream: NativeFile, + buffer_size: int, + memory_pool: MemoryPool | None = None, + ) -> None: ... + def detach(self) -> NativeFile: ... + +class TransformInputStream(NativeFile): + def __init__( + self, stream: NativeFile, transform_func: Callable[[Buffer], SupportPyBuffer] + ) -> None: ... + +def transcoding_input_stream( + stream: NativeFile, src_encoding: str, dest_encoding: str +) -> TransformInputStream: ... +def py_buffer(obj: SupportPyBuffer) -> Buffer: ... +def foreign_buffer(address: int, size: int, base: object | None = None) -> Buffer: ... +def as_buffer(o: Buffer | SupportPyBuffer) -> Buffer: ... + +# --------------------------------------------------------------------- + +class CacheOptions(_Weakrefable): + hole_size_limit: int + range_size_limit: int + lazy: bool + prefetch_limit: int + def __init__( + self, + *, + hole_size_limit: int | None = None, + range_size_limit: int | None = None, + lazy: bool | None = None, + prefetch_limit: int | None = None, + ) -> None: ... + @staticmethod + def from_network_metrics( + time_to_first_byte_millis: int, + transfer_bandwidth_mib_per_sec: int, + ideal_bandwidth_utilization_frac: float = 0.9, + max_ideal_request_size_mib: int = 64, + ) -> CacheOptions: ... + +class Codec(_Weakrefable): + def __init__( + self, compression: Compression, compression_level: int | None = None + ) -> None: ... + @staticmethod + def detect(path: StrPath) -> Codec: ... + @staticmethod + def is_available(compression: Compression) -> bool: ... + @staticmethod + def supports_compression_level(compression: Compression) -> bool: ... + @staticmethod + def default_compression_level(compression: Compression) -> int: ... + @staticmethod + def minimum_compression_level(compression: Compression) -> int: ... + @staticmethod + def maximum_compression_level(compression: Compression) -> int: ... + @property + def name(self) -> Compression: ... + @property + def compression_level(self) -> int: ... + @overload + def compress( + self, + buf: Buffer | bytes | SupportPyBuffer, + asbytes: Literal[False] = False, + memory_pool: MemoryPool | None = None, + ) -> Buffer: ... + @overload + def compress( + self, + buf: Buffer | bytes | SupportPyBuffer, + asbytes: Literal[True], + memory_pool: MemoryPool | None = None, + ) -> bytes: ... + @overload + def compress( + self, + buf: Buffer | bytes | SupportPyBuffer, + asbytes: bool = False, + memory_pool: MemoryPool | None = None, + ) -> Buffer | bytes: ... + @overload + def decompress( + self, + buf: Buffer | bytes | SupportPyBuffer, + decompressed_size: int | None = None, + asbytes: Literal[False] = False, + memory_pool: MemoryPool | None = None, + ) -> Buffer: ... + @overload + def decompress( + self, + buf: Buffer | bytes | SupportPyBuffer, + decompressed_size: int | None = None, + asbytes: Literal[True] = ..., + memory_pool: MemoryPool | None = None, + ) -> bytes: ... + @overload + def decompress( + self, + buf: Buffer | bytes | SupportPyBuffer, + decompressed_size: int | None = None, + asbytes: bool = False, + memory_pool: MemoryPool | None = None, + ) -> Buffer | bytes: ... + +@overload +def compress( + buf: Buffer | bytes | SupportPyBuffer, + codec: Compression = "lz4", + asbytes: Literal[False] = False, + memory_pool: MemoryPool | None = None, +) -> Buffer: ... +@overload +def compress( + buf: Buffer | bytes | SupportPyBuffer, + codec: Compression = "lz4", + asbytes: Literal[True] = ..., + memory_pool: MemoryPool | None = None, +) -> bytes: ... +@overload +def compress( + buf: Buffer | bytes | SupportPyBuffer, + codec: Compression = "lz4", + asbytes: bool = False, + memory_pool: MemoryPool | None = None, +) -> Buffer | bytes: ... +@overload +def decompress( + buf: Buffer | bytes | SupportPyBuffer, + decompressed_size: int | None = None, + codec: Compression = "lz4", + asbytes: Literal[False] = False, + memory_pool: MemoryPool | None = None, +) -> Buffer: ... +@overload +def decompress( + buf: Buffer | bytes | SupportPyBuffer, + decompressed_size: int | None = None, + codec: Compression = "lz4", + asbytes: Literal[True] = ..., + memory_pool: MemoryPool | None = None, +) -> bytes: ... +@overload +def decompress( + buf: Buffer | bytes | SupportPyBuffer, + decompressed_size: int | None = None, + codec: Compression = "lz4", + asbytes: bool = False, + memory_pool: MemoryPool | None = None, +) -> Buffer | bytes: ... +def input_stream( + source: StrPath | Buffer | IOBase, + compression: Literal["detect", "bz2", "brotli", "gzip", "lz4", "zstd"] = "detect", + buffer_size: int | None = None, +) -> BufferReader: ... +def output_stream( + source: StrPath | Buffer | IOBase, + compression: Literal["detect", "bz2", "brotli", "gzip", "lz4", "zstd"] = "detect", + buffer_size: int | None = None, +) -> NativeFile: ... + +__all__ = [ + "io_thread_count", + "set_io_thread_count", + "NativeFile", + "PythonFile", + "MemoryMappedFile", + "memory_map", + "create_memory_map", + "OSFile", + "FixedSizeBufferWriter", + "Buffer", + "ResizableBuffer", + "allocate_buffer", + "BufferOutputStream", + "MockOutputStream", + "BufferReader", + "CompressedInputStream", + "CompressedOutputStream", + "BufferedInputStream", + "BufferedOutputStream", + "TransformInputStream", + "transcoding_input_stream", + "py_buffer", + "foreign_buffer", + "as_buffer", + "CacheOptions", + "Codec", + "compress", + "decompress", + "input_stream", + "output_stream", +] diff --git a/python/pyarrow-stubs/__lib/ipc.pyi b/python/pyarrow-stubs/__lib/ipc.pyi index c84964043e4..4c8f6b3c446 100644 --- a/python/pyarrow-stubs/__lib/ipc.pyi +++ b/python/pyarrow-stubs/__lib/ipc.pyi @@ -15,11 +15,260 @@ # specific language governing permissions and limitations # under the License. -# Placeholder stub - complete annotations in future PR. -# At runtime, these symbols are provided by the pyarrow.lib C extension. +import enum +from collections.abc import Iterable, Iterator, Mapping +from io import IOBase +from typing import Any, Literal, NamedTuple, Self -from typing import Any, TypeAlias +import pandas as pd +from pyarrow._stubs_typing import SupportPyBuffer +from pyarrow.lib import ( + Buffer, + BufferReader, + Codec, + DictionaryMemo, + KeyValueMetadata, + MemoryPool, + NativeFile, + RecordBatch, + Schema, + Table, + Tensor, + _Weakrefable, +) +from typing_extensions import CapsuleType -RecordBatchReader: TypeAlias = Any +class MetadataVersion(enum.IntEnum): + V1 = 0 + V2 = 1 + V3 = 2 + V4 = 3 + V5 = 4 -def __getattr__(name: str) -> Any: ... +class Alignment(enum.IntEnum): + Any = 0 + At64Byte = 64 + DataTypeSpecific = -3 + +class WriteStats(NamedTuple): + num_messages: int + num_record_batches: int + num_dictionary_batches: int + num_dictionary_deltas: int + num_replaced_dictionaries: int + +class ReadStats(NamedTuple): + num_messages: int + num_record_batches: int + num_dictionary_batches: int + num_dictionary_deltas: int + num_replaced_dictionaries: int + +class IpcReadOptions(_Weakrefable): + ensure_native_endian: bool + use_threads: bool + ensure_alignment: Alignment + included_fields: list[int] | None + + def __init__( + self, + *, + ensure_native_endian: bool = True, + use_threads: bool = True, + ensure_alignment: Alignment = ..., + included_fields: list[int] | None = None, + ) -> None: ... + +class IpcWriteOptions(_Weakrefable): + metadata_version: Any + allow_64bit: bool + use_legacy_format: bool + compression: Any + use_threads: bool + emit_dictionary_deltas: bool + unify_dictionaries: bool + + def __init__( + self, + *, + metadata_version: MetadataVersion = ..., + allow_64bit: bool = False, + use_legacy_format: bool = False, + compression: Codec | Literal["lz4", "zstd"] | None = None, + use_threads: bool = True, + emit_dictionary_deltas: bool = False, + unify_dictionaries: bool = False, + ) -> None: ... + +class Message(_Weakrefable): + @property + def type(self) -> str: ... + @property + def metadata(self) -> Buffer: ... + @property + def metadata_version(self) -> MetadataVersion: ... + @property + def body(self) -> Buffer | None: ... + def equals(self, other: Message) -> bool: ... + def serialize_to( + self, + sink: NativeFile, + alignment: int = 8, + memory_pool: MemoryPool | None = None, + ) -> None: ... + def serialize( + self, alignment: int = 8, memory_pool: MemoryPool | None = None + ) -> Buffer: ... + +class MessageReader(_Weakrefable): + @staticmethod + def open_stream( + source: bytes | NativeFile | IOBase | SupportPyBuffer, + ) -> MessageReader: ... + def __iter__(self) -> Self: ... + def read_next_message(self) -> Message: ... + + __next__ = read_next_message + +# ---------------------------------------------------------------------- +# File and stream readers and writers + +class _CRecordBatchWriter(_Weakrefable): + def write(self, table_or_batch: Table | RecordBatch) -> None: ... + def write_batch( + self, + batch: RecordBatch, + custom_metadata: Mapping[bytes, bytes] | KeyValueMetadata | None = None, + ) -> None: ... + def write_table(self, table: Table, max_chunksize: int | None = None) -> None: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, exc_type: object, exc_val: object, exc_tb: object) -> None: ... + @property + def stats(self) -> WriteStats: ... + +class _RecordBatchStreamWriter(_CRecordBatchWriter): + @property + def _use_legacy_format(self) -> bool: ... + @property + def _metadata_version(self) -> MetadataVersion: ... + def _open( + self, + sink: Any, + schema: Schema, + options: IpcWriteOptions = ..., + ) -> None: ... + +class _ReadPandasMixin: + def read_pandas(self, **options: Any) -> pd.DataFrame: ... + +class RecordBatchReader(_ReadPandasMixin, _Weakrefable): + def __iter__(self) -> Self: ... + def read_next_batch(self) -> RecordBatch: ... + + __next__ = read_next_batch + @property + def schema(self) -> Schema: ... + def read_next_batch_with_custom_metadata(self) -> RecordBatchWithMetadata: ... + def iter_batches_with_custom_metadata( + self, + ) -> Iterator[RecordBatchWithMetadata]: ... + def read_all(self) -> Table: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, exc_type: object, exc_val: object, exc_tb: object) -> None: ... + def cast(self, target_schema: Schema) -> Self: ... + def _export_to_c(self, out_ptr: int) -> None: ... + @staticmethod + def _import_from_c(in_ptr: int) -> RecordBatchReader: ... + def __arrow_c_stream__( + self, requested_schema: CapsuleType | None = None + ) -> CapsuleType: ... + @staticmethod + def _import_from_c_capsule(stream: CapsuleType) -> RecordBatchReader: ... + @staticmethod + def from_stream(data: Any, schema: Schema | None = None) -> RecordBatchReader: ... + @staticmethod + def from_batches( + schema: Schema, batches: Iterable[RecordBatch] + ) -> RecordBatchReader: ... + +class _RecordBatchStreamReader(RecordBatchReader): + @property + def stats(self) -> ReadStats: ... + def _open( + self, + source: Any, + options: IpcReadOptions | None = ..., + memory_pool: MemoryPool | None = None, + ) -> Self: ... + +class _RecordBatchFileWriter(_RecordBatchStreamWriter): ... + +class RecordBatchWithMetadata(NamedTuple): + batch: RecordBatch + custom_metadata: KeyValueMetadata + +class _RecordBatchFileReader(_ReadPandasMixin, _Weakrefable): + @property + def num_record_batches(self) -> int: ... + def get_batch(self, i: int) -> RecordBatch: ... + + get_record_batch = get_batch + def get_batch_with_custom_metadata(self, i: int) -> RecordBatchWithMetadata: ... + def read_all(self) -> Table: ... + def __enter__(self) -> Self: ... + def __exit__(self, exc_type: object, exc_val: object, exc_tb: object) -> None: ... + @property + def schema(self) -> Schema: ... + @property + def stats(self) -> ReadStats: ... + @property + def metadata(self) -> KeyValueMetadata | None: ... + def _open( + self, + source: Any, + footer_offset: int | None = None, + options: IpcReadOptions | None = ..., + memory_pool: MemoryPool | None = None, + ) -> Self: ... + +def get_tensor_size(tensor: Tensor) -> int: ... +def get_record_batch_size(batch: RecordBatch) -> int: ... +def write_tensor(tensor: Tensor, dest: NativeFile) -> int: ... +def read_tensor(source: NativeFile) -> Tensor: ... +def read_message(source: NativeFile | IOBase | SupportPyBuffer) -> Message: ... +def read_schema( + obj: Buffer | Message | BufferReader, dictionary_memo: DictionaryMemo | None = None +) -> Schema: ... +def read_record_batch( + obj: Message | SupportPyBuffer, + schema: Schema, + dictionary_memo: DictionaryMemo | None = None, +) -> RecordBatch: ... + +__all__ = [ + "MetadataVersion", + "Alignment", + "WriteStats", + "ReadStats", + "IpcReadOptions", + "IpcWriteOptions", + "Message", + "MessageReader", + "_CRecordBatchWriter", + "_RecordBatchStreamWriter", + "_ReadPandasMixin", + "RecordBatchReader", + "_RecordBatchStreamReader", + "_RecordBatchFileWriter", + "RecordBatchWithMetadata", + "_RecordBatchFileReader", + "get_tensor_size", + "get_record_batch_size", + "write_tensor", + "read_tensor", + "read_message", + "read_schema", + "read_record_batch", +] diff --git a/python/pyarrow-stubs/__lib/scalar.pyi b/python/pyarrow-stubs/__lib/scalar.pyi index f206434db26..ea71b921319 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: ... @@ -274,7 +282,7 @@ class ListScalar(Scalar, Sequence[Scalar]): def values(self) -> Array | None: ... def __len__(self) -> int: ... # Only integer indices, unlike Sequence, which also takes slices. - def __getitem__(self, i: SupportsIndex) -> Scalar: ... # type: ignore[override] + def __getitem__(self, i: SupportsIndex, /) -> Scalar: ... # type: ignore[override] def __iter__(self) -> Iterator[Scalar]: ... def as_py( self, *, maps_as_pydicts: MapsAsPydicts | None = None @@ -290,7 +298,7 @@ class StructScalar(Scalar, Mapping[str, Scalar]): def __iter__(self) -> Iterator[str]: ... def __contains__(self, key: object, /) -> bool: ... # Look up a field by name or position. - def __getitem__(self, key: str | bytes | int) -> Scalar: ... + def __getitem__(self, key: str | bytes | int, /) -> Scalar: ... # The runtime yields a generator instead of a Mapping view def items(self) -> Iterator[tuple[str, Scalar]]: ... # type: ignore[override] def as_py( @@ -302,9 +310,9 @@ class StructScalar(Scalar, Mapping[str, Scalar]): # methods are omitted (see GH-55866). class MapScalar(ListScalar): @overload # type: ignore[override] - def __getitem__(self, i: SupportsIndex) -> tuple[Scalar, Scalar]: ... + def __getitem__(self, i: SupportsIndex, /) -> tuple[Scalar, Scalar]: ... @overload - def __getitem__(self, i: str | bytes) -> Scalar: ... + def __getitem__(self, i: str | bytes, /) -> Scalar: ... def __iter__(self) -> Iterator[tuple[Any, Any]]: ... # type: ignore[override] def keys(self) -> list[Any]: ... # A list of (key, item) tuples, or a dict if maps_as_pydicts is given. diff --git a/python/pyarrow-stubs/__lib/table.pyi b/python/pyarrow-stubs/__lib/table.pyi index 7b5e51fa7ae..58314228d4c 100644 --- a/python/pyarrow-stubs/__lib/table.pyi +++ b/python/pyarrow-stubs/__lib/table.pyi @@ -183,9 +183,9 @@ class ChunkedArray(_PandasConvertible[pd.Series]): def get_total_buffer_size(self) -> int: ... def __sizeof__(self) -> int: ... @overload - def __getitem__(self, key: SupportsIndex) -> Scalar: ... + def __getitem__(self, key: SupportsIndex, /) -> Scalar: ... @overload - def __getitem__(self, key: builtins.slice) -> ChunkedArray: ... + def __getitem__(self, key: builtins.slice, /) -> ChunkedArray: ... __hash__: ClassVar[None] # type: ignore[assignment] def is_null(self, *, nan_is_null: bool = False) -> ChunkedArray: ... def is_nan(self) -> ChunkedArray: ... @@ -268,9 +268,9 @@ class _Tabular(_PandasConvertible[pd.DataFrame], Generic[_ColumnT]): self, nan_as_null: bool = False, allow_copy: bool = True ) -> _PyArrowDataFrame: ... @overload - def __getitem__(self, key: int | str) -> _ColumnT: ... + def __getitem__(self, key: int | str, /) -> _ColumnT: ... @overload - def __getitem__(self, key: slice) -> Self: ... + def __getitem__(self, key: slice, /) -> Self: ... def __len__(self) -> int: ... __hash__: ClassVar[None] # type: ignore[assignment] def column(self, i: int | str) -> _ColumnT: ... 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/_csv.pyi b/python/pyarrow-stubs/_csv.pyi new file mode 100644 index 00000000000..a6f29338634 --- /dev/null +++ b/python/pyarrow-stubs/_csv.pyi @@ -0,0 +1,170 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from collections.abc import Callable, Sequence +from typing import IO, Any, Literal, NamedTuple + +from _typeshed import StrPath + +from . import lib + +class ReadOptions(lib._Weakrefable): + use_threads: bool + block_size: int | None + skip_rows: int + skip_rows_after_names: int + column_names: Sequence[str] | None + autogenerate_column_names: bool + encoding: str + + def __init__( + self, + use_threads: bool | None = None, + *, + block_size: int | None = None, + skip_rows: int | None = None, + skip_rows_after_names: int | None = None, + column_names: Sequence[str] | None = None, + autogenerate_column_names: bool | None = None, + encoding: str = "utf8", + ) -> None: ... + def equals(self, other: ReadOptions) -> bool: ... + def validate(self) -> None: ... + +class ParseOptions(lib._Weakrefable): + delimiter: str + quote_char: str | Literal[False] + double_quote: bool + escape_char: str | Literal[False] + newlines_in_values: bool + ignore_empty_lines: bool + invalid_row_handler: Callable[[InvalidRow], str] | None + + def __init__( + self, + delimiter: str | None = None, + *, + quote_char: str | Literal[False] | None = None, + double_quote: bool | None = None, + escape_char: str | Literal[False] | None = None, + newlines_in_values: bool | None = None, + ignore_empty_lines: bool | None = None, + invalid_row_handler: Callable[[InvalidRow], str] | None = None, + ) -> None: ... + def equals(self, other: ParseOptions) -> bool: ... + def validate(self) -> None: ... + +class ConvertOptions(lib._Weakrefable): + check_utf8: bool + column_types: ( + lib.Schema | dict[str, lib.DataType] | Sequence[tuple[str, lib.DataType]] | None + ) + null_values: list[str] | None + true_values: list[str] | None + false_values: list[str] | None + decimal_point: str + strings_can_be_null: bool + quoted_strings_can_be_null: bool + include_columns: list[str] | None + include_missing_columns: bool + auto_dict_encode: bool + auto_dict_max_cardinality: int | None + timestamp_parsers: Sequence[str | lib._Weakrefable] | None + + def __init__( + self, + check_utf8: bool | None = None, + *, + column_types: ( + lib.Schema + | dict[str, lib.DataType] + | Sequence[tuple[str, lib.DataType]] + | None + ) = None, + null_values: Sequence[str] | None = None, + true_values: Sequence[str] | None = None, + false_values: Sequence[str] | None = None, + decimal_point: str | None = None, + strings_can_be_null: bool | None = None, + quoted_strings_can_be_null: bool | None = None, + include_columns: Sequence[str] | None = None, + include_missing_columns: bool | None = None, + auto_dict_encode: bool | None = None, + auto_dict_max_cardinality: int | None = None, + timestamp_parsers: Sequence[str | lib._Weakrefable] | None = None, + ) -> None: ... + def equals(self, other: ConvertOptions) -> bool: ... + def validate(self) -> None: ... + +class WriteOptions(lib._Weakrefable): + include_header: bool + batch_size: int + delimiter: str + quoting_style: Literal["needed", "all_valid", "none"] + quoting_header: Literal["needed", "all_valid", "none"] + + def __init__( + self, + include_header: bool = True, + *, + batch_size: int = 1024, + delimiter: str = ",", + quoting_style: Literal["needed", "all_valid", "none"] = "needed", + quoting_header: Literal["needed", "all_valid", "none"] = "needed", + ) -> None: ... + def validate(self) -> None: ... + +class InvalidRow(NamedTuple): + expected_columns: int + actual_columns: int + number: int | None + text: str + +class CSVWriter(lib._CRecordBatchWriter): + def __init__( + self, + sink: StrPath | lib.NativeFile | IO[Any], + schema: lib.Schema, + write_options: WriteOptions | None = None, + *, + memory_pool: lib.MemoryPool | None = None, + ) -> None: ... + +class CSVStreamingReader(lib.RecordBatchReader): ... + +ISO8601: lib._Weakrefable + +def open_csv( + input_file: StrPath | lib.NativeFile | IO[Any], + read_options: ReadOptions | None = None, + parse_options: ParseOptions | None = None, + convert_options: ConvertOptions | None = None, + memory_pool: lib.MemoryPool | None = None, +) -> CSVStreamingReader: ... +def read_csv( + input_file: StrPath | lib.NativeFile | IO[Any], + read_options: ReadOptions | None = None, + parse_options: ParseOptions | None = None, + convert_options: ConvertOptions | None = None, + memory_pool: lib.MemoryPool | None = None, +) -> lib.Table: ... +def write_csv( + data: lib.RecordBatch | lib.Table, + output_file: StrPath | lib.NativeFile | IO[Any], + write_options: WriteOptions | None = None, + memory_pool: lib.MemoryPool | None = None, +) -> None: ... diff --git a/python/pyarrow-stubs/_feather.pyi b/python/pyarrow-stubs/_feather.pyi new file mode 100644 index 00000000000..ebc922ae084 --- /dev/null +++ b/python/pyarrow-stubs/_feather.pyi @@ -0,0 +1,47 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from collections.abc import Sequence +from typing import IO, Any, Literal, Self + +from _typeshed import StrPath + +from .lib import Buffer, NativeFile, Table, _Weakrefable + +class FeatherError(Exception): ... + +def write_feather( + table: Table, + dest: StrPath | IO[Any] | NativeFile, + compression: str | None = None, + compression_level: int | None = None, + chunksize: int | None = None, + version: Literal[1, 2] = 2, +) -> None: ... + +class FeatherReader(_Weakrefable): + def __new__( + cls, + source: StrPath | IO[Any] | NativeFile | Buffer, + use_memory_map: bool = True, + use_threads: bool = True, + ) -> Self: ... + @property + def version(self) -> str: ... + def read(self) -> Table: ... + def read_indices(self, indices: Sequence[int]) -> Table: ... + def read_names(self, names: Sequence[str]) -> Table: ... diff --git a/python/pyarrow-stubs/_json.pyi b/python/pyarrow-stubs/_json.pyi new file mode 100644 index 00000000000..042c18d5938 --- /dev/null +++ b/python/pyarrow-stubs/_json.pyi @@ -0,0 +1,59 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from typing import IO, Any, Literal + +from _typeshed import StrPath + +from .lib import MemoryPool, NativeFile, RecordBatchReader, Schema, Table, _Weakrefable + +class ReadOptions(_Weakrefable): + use_threads: bool + block_size: int + + def __init__( + self, use_threads: bool | None = None, block_size: int | None = None + ) -> None: ... + def equals(self, other: ReadOptions) -> bool: ... + +class ParseOptions(_Weakrefable): + explicit_schema: Schema + newlines_in_values: bool + unexpected_field_behavior: Literal["ignore", "error", "infer"] + + def __init__( + self, + explicit_schema: Schema | None = None, + newlines_in_values: bool | None = None, + unexpected_field_behavior: Literal["ignore", "error", "infer"] = "infer", + ) -> None: ... + def equals(self, other: ParseOptions) -> bool: ... + +class JSONStreamingReader(RecordBatchReader): ... + +def read_json( + input_file: StrPath | NativeFile | IO[Any], + read_options: ReadOptions | None = None, + parse_options: ParseOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> Table: ... +def open_json( + input_file: StrPath | NativeFile | IO[Any], + read_options: ReadOptions | None = None, + parse_options: ParseOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> JSONStreamingReader: ... diff --git a/python/pyarrow-stubs/_orc.pyi b/python/pyarrow-stubs/_orc.pyi new file mode 100644 index 00000000000..63dd07c7e7a --- /dev/null +++ b/python/pyarrow-stubs/_orc.pyi @@ -0,0 +1,77 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from typing import IO, Any, Literal, Self + +from .lib import ( + Buffer, + KeyValueMetadata, + MemoryPool, + NativeFile, + RecordBatch, + Schema, + Table, + _Weakrefable, +) + +class ORCReader(_Weakrefable): + def __new__(cls, memory_pool: MemoryPool | None = None) -> Self: ... + def open( + self, source: str | NativeFile | Buffer, use_memory_map: bool = True + ) -> None: ... + def metadata(self) -> KeyValueMetadata: ... + def schema(self) -> Schema: ... + def nrows(self) -> int: ... + def nstripes(self) -> int: ... + def file_version(self) -> str: ... + def software_version(self) -> str: ... + def compression( + self, + ) -> Literal["UNCOMPRESSED", "ZLIB", "SNAPPY", "LZ4", "ZSTD"]: ... + def compression_size(self) -> int: ... + def row_index_stride(self) -> int: ... + def writer(self) -> str: ... + def writer_version(self) -> str: ... + def nstripe_statistics(self) -> int: ... + def content_length(self) -> int: ... + def stripe_statistics_length(self) -> int: ... + def file_footer_length(self) -> int: ... + def file_postscript_length(self) -> int: ... + def file_length(self) -> int: ... + def serialized_file_tail(self) -> int: ... + def read_stripe(self, n: int, columns: list[str] | None = None) -> RecordBatch: ... + def read(self, columns: list[str] | None = None) -> Table: ... + +class ORCWriter(_Weakrefable): + def open( + self, + where: str | NativeFile | IO[Any], + *, + file_version: str | None = None, + batch_size: int | None = None, + stripe_size: int | None = None, + compression: Any = None, + compression_block_size: int | None = None, + compression_strategy: Any = None, + row_index_stride: int | None = None, + padding_tolerance: float | None = None, + dictionary_key_size_threshold: float | None = None, + bloom_filter_columns: list[int] | None = None, + bloom_filter_fpp: float | None = None, + ) -> None: ... + def write(self, table: Table) -> None: ... + def close(self) -> None: ... diff --git a/python/pyarrow-stubs/_stubs_typing.pyi b/python/pyarrow-stubs/_stubs_typing.pyi index 90a79999511..12760f3e0c8 100644 --- a/python/pyarrow-stubs/_stubs_typing.pyi +++ b/python/pyarrow-stubs/_stubs_typing.pyi @@ -15,15 +15,21 @@ # 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 +from _typeshed import SupportsRead, SupportsWrite from numpy.typing import NDArray from pyarrow.lib import Array, ChunkedArray from pyarrow import lib +Compression: TypeAlias = Literal[ + "gzip", "bz2", "brotli", "lz4", "lz4_frame", "lz4_raw", "zstd", "snappy" +] Order: TypeAlias = Literal["ascending", "descending"] MapsAsPydicts: TypeAlias = Literal["lossy", "strict"] NullEncoding: TypeAlias = Literal["mask", "encode"] @@ -36,6 +42,18 @@ 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 SupportPyBuffer(Protocol): + def __buffer__(self, flags: int, /) -> memoryview: ... + +# Needed for NativeFile.download() +# Though it only writes to the stream, it checks for a read method +class SupportsReadWrite(SupportsRead[bytes], SupportsWrite[bytes], Protocol): ... + 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-stubs/csv.pyi b/python/pyarrow-stubs/csv.pyi new file mode 100644 index 00000000000..2061f96e530 --- /dev/null +++ b/python/pyarrow-stubs/csv.pyi @@ -0,0 +1,30 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from pyarrow._csv import ( + ISO8601 as ISO8601, + ConvertOptions as ConvertOptions, + CSVStreamingReader as CSVStreamingReader, + CSVWriter as CSVWriter, + InvalidRow as InvalidRow, + ParseOptions as ParseOptions, + ReadOptions as ReadOptions, + WriteOptions as WriteOptions, + open_csv as open_csv, + read_csv as read_csv, + write_csv as write_csv, +) diff --git a/python/pyarrow-stubs/feather.pyi b/python/pyarrow-stubs/feather.pyi new file mode 100644 index 00000000000..287871edbe2 --- /dev/null +++ b/python/pyarrow-stubs/feather.pyi @@ -0,0 +1,62 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from collections.abc import Iterable +from typing import IO, Any, Literal + +import pandas as pd +from _typeshed import StrPath +from pyarrow import lib +from pyarrow.lib import Table + +from ._feather import FeatherError as FeatherError + +class FeatherDataset: + path_or_paths: str | list[str] + validate_schema: bool + + def __init__( + self, path_or_paths: str | list[str], validate_schema: bool = True + ) -> None: ... + def read_table(self, columns: list[str] | None = None) -> Table: ... + def validate_schemas(self, piece: Any, table: Table) -> None: ... + def read_pandas( + self, columns: list[str] | None = None, use_threads: bool = True + ) -> pd.DataFrame: ... + +def check_chunked_overflow(name: str, col: Any) -> None: ... +def write_feather( + df: pd.DataFrame | Table | lib.ChunkedArray, + dest: StrPath | IO[Any] | lib.NativeFile, + compression: Literal["zstd", "lz4", "uncompressed", "snappy"] | None = None, + compression_level: int | None = None, + chunksize: int | None = None, + version: Literal[1, 2] = 2, +) -> None: ... +def read_feather( + source: StrPath | IO[Any] | lib.NativeFile, + columns: list[str] | None = None, + use_threads: bool = True, + memory_map: bool = False, + **kwargs: Any, +) -> pd.DataFrame: ... +def read_table( + source: StrPath | IO[Any] | lib.NativeFile, + columns: Iterable[str | int] | None = None, + memory_map: bool = False, + use_threads: bool = True, +) -> Table: ... diff --git a/python/pyarrow-stubs/ipc.pyi b/python/pyarrow-stubs/ipc.pyi new file mode 100644 index 00000000000..b1daedb27db --- /dev/null +++ b/python/pyarrow-stubs/ipc.pyi @@ -0,0 +1,113 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from io import IOBase + +from _typeshed import StrPath +import pandas as pd +import pyarrow.lib as lib + +from pyarrow.lib import ( + Alignment as Alignment, + IpcReadOptions as IpcReadOptions, + IpcWriteOptions as IpcWriteOptions, + Message as Message, + MessageReader as MessageReader, + MetadataVersion as MetadataVersion, + ReadStats as ReadStats, + RecordBatchReader as RecordBatchReader, + WriteStats as WriteStats, + _ReadPandasMixin as _ReadPandasMixin, + get_record_batch_size as get_record_batch_size, + get_tensor_size as get_tensor_size, + read_message as read_message, + read_record_batch as read_record_batch, + read_schema as read_schema, + read_tensor as read_tensor, + write_tensor as write_tensor, +) + +class RecordBatchStreamReader(lib._RecordBatchStreamReader): + def __init__( + self, + source: bytes | lib.Buffer | lib.NativeFile | IOBase, + *, + options: IpcReadOptions | None = None, + memory_pool: lib.MemoryPool | None = None, + ) -> None: ... + +class RecordBatchStreamWriter(lib._RecordBatchStreamWriter): + def __init__( + self, + sink: str | lib.NativeFile | IOBase, + schema: lib.Schema, + *, + options: IpcWriteOptions | None = None, + ) -> None: ... + +class RecordBatchFileReader(lib._RecordBatchFileReader): + def __init__( + self, + source: bytes | lib.Buffer | lib.NativeFile | IOBase, + footer_offset: int | None = None, + *, + options: IpcReadOptions | None = None, + memory_pool: lib.MemoryPool | None = None, + ) -> None: ... + +class RecordBatchFileWriter(lib._RecordBatchFileWriter): + def __init__( + self, + sink: str | lib.NativeFile | IOBase, + schema: lib.Schema, + *, + options: IpcWriteOptions | None = None, + metadata: lib.KeyValueMetadata | dict[bytes, bytes] | None = None, + ) -> None: ... + +def new_stream( + sink: str | lib.NativeFile | IOBase, + schema: lib.Schema, + *, + options: IpcWriteOptions | None = None, +) -> RecordBatchStreamWriter: ... +def open_stream( + source: bytes | int | lib.Buffer | lib.NativeFile | IOBase, + *, + options: IpcReadOptions | None = None, + memory_pool: lib.MemoryPool | None = None, +) -> RecordBatchStreamReader: ... +def new_file( + sink: str | lib.NativeFile | IOBase, + schema: lib.Schema, + *, + options: IpcWriteOptions | None = None, + metadata: lib.KeyValueMetadata | dict[bytes, bytes] | None = None, +) -> RecordBatchFileWriter: ... +def open_file( + source: StrPath | bytes | lib.Buffer | lib.NativeFile | IOBase, + footer_offset: int | None = None, + *, + options: IpcReadOptions | None = None, + memory_pool: lib.MemoryPool | None = None, +) -> RecordBatchFileReader: ... +def serialize_pandas( + df: pd.DataFrame, *, nthreads: int | None = None, preserve_index: bool | None = None +) -> lib.Buffer: ... +def deserialize_pandas( + buf: lib.Buffer, *, use_threads: bool = True +) -> pd.DataFrame: ... diff --git a/python/pyarrow-stubs/json.pyi b/python/pyarrow-stubs/json.pyi new file mode 100644 index 00000000000..d67cf434b23 --- /dev/null +++ b/python/pyarrow-stubs/json.pyi @@ -0,0 +1,23 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from pyarrow._json import ( + ParseOptions as ParseOptions, + ReadOptions as ReadOptions, + open_json as open_json, + read_json as read_json, +) diff --git a/python/pyarrow-stubs/lib.pyi b/python/pyarrow-stubs/lib.pyi index 818241e224e..01fb54cbb34 100644 --- a/python/pyarrow-stubs/lib.pyi +++ b/python/pyarrow-stubs/lib.pyi @@ -27,6 +27,7 @@ from pyarrow.__lib.config import * # noqa: F401,F403 from pyarrow.__lib.device import * # noqa: F401,F403 from pyarrow.__lib.error import * # noqa: F401,F403 from pyarrow.__lib.io import * # noqa: F401,F403 +from pyarrow.__lib.ipc import * # noqa: F401,F403 from pyarrow.__lib.memory import * # noqa: F401,F403 from pyarrow.__lib.scalar import * # noqa: F401,F403 from pyarrow.__lib.table import * # noqa: F401,F403 diff --git a/python/pyarrow-stubs/orc.pyi b/python/pyarrow-stubs/orc.pyi new file mode 100644 index 00000000000..d47b6a184ee --- /dev/null +++ b/python/pyarrow-stubs/orc.pyi @@ -0,0 +1,115 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from collections.abc import Sequence +from typing import IO, Any, Literal, Self + +from _typeshed import StrPath + +from . import _orc +from .lib import KeyValueMetadata, NativeFile, RecordBatch, Schema, Table + +class ORCFile: + reader: _orc.ORCReader + def __init__(self, source: StrPath | NativeFile | IO[Any]) -> None: ... + @property + def metadata(self) -> KeyValueMetadata: ... + @property + def schema(self) -> Schema: ... + @property + def nrows(self) -> int: ... + @property + def nstripes(self) -> int: ... + @property + def file_version(self) -> str: ... + @property + def software_version(self) -> str: ... + @property + def compression( + self, + ) -> Literal["UNCOMPRESSED", "ZLIB", "SNAPPY", "LZ4", "ZSTD"]: ... + @property + def compression_size(self) -> int: ... + @property + def writer(self) -> str: ... + @property + def writer_version(self) -> str: ... + @property + def row_index_stride(self) -> int: ... + @property + def nstripe_statistics(self) -> int: ... + @property + def content_length(self) -> int: ... + @property + def stripe_statistics_length(self) -> int: ... + @property + def file_footer_length(self) -> int: ... + @property + def file_postscript_length(self) -> int: ... + @property + def file_length(self) -> int: ... + def read_stripe( + self, n: int, columns: Sequence[str | int] | None = None + ) -> RecordBatch: ... + def read(self, columns: Sequence[str | int] | None = None) -> Table: ... + +class ORCWriter: + writer: _orc.ORCWriter + is_open: bool + + def __init__( + self, + where: StrPath | NativeFile | IO[Any], + *, + file_version: str = "0.12", + batch_size: int = 1024, + stripe_size: int = ..., + compression: str = "uncompressed", + compression_block_size: int = 65536, + compression_strategy: str = "speed", + row_index_stride: int = 10000, + padding_tolerance: float = 0.0, + dictionary_key_size_threshold: float = 0.0, + bloom_filter_columns: Sequence[int] | None = None, + bloom_filter_fpp: float = 0.05, + ) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: object, **kwargs: Any) -> None: ... + def write(self, table: Table) -> None: ... + def close(self) -> None: ... + +def read_table( + source: StrPath | NativeFile | IO[Any], + columns: Sequence[str | int] | None = None, + filesystem: Any = None, +) -> Table: ... +def write_table( + table: Table, + where: StrPath | NativeFile | IO[Any], + *, + file_version: str = "0.12", + batch_size: int = 1024, + stripe_size: int = ..., + compression: str = "uncompressed", + compression_block_size: int = 65536, + compression_strategy: str = "speed", + row_index_stride: int = 10000, + padding_tolerance: float = 0.0, + dictionary_key_size_threshold: float = 0.0, + bloom_filter_columns: Sequence[int] | None = None, + bloom_filter_fpp: float = 0.05, +) -> None: ... 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]]