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_array.py b/python/pyarrow-stubs-tests/test_array.py index d64e4277907..f321bdfb247 100644 --- a/python/pyarrow-stubs-tests/test_array.py +++ b/python/pyarrow-stubs-tests/test_array.py @@ -41,8 +41,8 @@ def test_array() -> None: check(assert_type(arr.null_count, int), int) check(assert_type(len(arr), int), int) check(assert_type(arr.to_pylist(), list[Any]), list) - # Scalars aren't annotated yet, so indexing returns Any, slice keeps the subclass - check(assert_type(arr[0], Any), pa.Int64Scalar) + # Indexing returns a Scalar, slice keeps the subclass + check(assert_type(arr[0], pa.Scalar), pa.Int64Scalar) check(assert_type(arr[1:], pa.Int64Array), pa.Int64Array) # Methods returning the same kind of array keep the subclass. @@ -89,8 +89,9 @@ def test_array_constructors() -> None: if TYPE_CHECKING: pa.array([1, 2], mask=[True, None]) # type: ignore[list-item] - # TODO: when scalars get stubs - # pa.array([1, 2], mask=pa.chunked_array([[True, False]])) + # Chunked arrays aren't accepted as a mask + chunked_mask = pa.chunked_array([[True, False]]) + pa.array([1, 2], mask=chunked_mask) # type: ignore[arg-type] def test_array_operators() -> None: @@ -114,7 +115,7 @@ def test_array_numpy() -> None: import numpy as np arr = cast(pa.Int64Array, pa.array([1, 2])) - check(assert_type(arr[np.int64(0)], Any), pa.Int64Scalar) + check(assert_type(arr[np.int64(0)], pa.Scalar), pa.Int64Scalar) check(assert_type(pa.infer_type(np.array([1])), pa.DataType), pa.DataType) offsets = np.array([0, 1, 2], dtype="int32") check(assert_type(pa.ListArray.from_arrays(offsets, [1, 2]), pa.ListArray), @@ -272,8 +273,8 @@ def test_chunked_array() -> None: check(assert_type(chunked.type, pa.DataType), pa.DataType) check(assert_type(chunked.num_chunks, int), int) check(assert_type(chunked.chunk(0), pa.Array), pa.Int64Array) - # Scalars aren't annotated yet, so indexing returns Any, slice keeps ChunkedArray - check(assert_type(chunked[0], Any), pa.Int64Scalar) + # Indexing returns a Scalar, slice keeps ChunkedArray + check(assert_type(chunked[0], pa.Scalar), pa.Int64Scalar) check(assert_type(chunked[1:], pa.ChunkedArray), pa.ChunkedArray) check(assert_type(chunked.chunks, list[pa.Array]), list) check(assert_type(chunked.combine_chunks(), pa.Array), pa.Int64Array) diff --git a/python/pyarrow-stubs-tests/test_compute.py b/python/pyarrow-stubs-tests/test_compute.py new file mode 100644 index 00000000000..ca0160d1fbe --- /dev/null +++ b/python/pyarrow-stubs-tests/test_compute.py @@ -0,0 +1,469 @@ +# 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 Buffer + +from _check import assert_type, check + +_Filtered: TypeAlias = pa.Array | pa.ChunkedArray | pa.RecordBatch | pa.Table + +_Quantile: TypeAlias = ( + pa.NumericArray + | pa.Decimal32Array + | pa.Decimal64Array + | pa.Decimal128Array + | pa.Decimal256Array +) + +_Numeric: TypeAlias = ( + pa.NumericArray + | pa.Decimal32Array + | pa.Decimal64Array + | pa.Decimal128Array + | pa.Decimal256Array + | pa.ChunkedArray +) + +_NumericOrTemporal: TypeAlias = _Quantile | pa.MonthDayNanoIntervalArray + + +def test_expression() -> None: + # Field references and literals + 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(pc.abs(field), pc.Expression) + check(pc.utf8_upper(field), pc.Expression) + + if TYPE_CHECKING: + # Expressions define __eq__ and are unhashable. + _: Hashable = field # type: ignore[assignment] # ty: ignore[invalid-assignment] # noqa: E501 + field.cast(1) # type: ignore[arg-type] + pc.field(1.0) # type: ignore[arg-type] + + +def test_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] + # TODO: test invalid code once the scalar stubs are annotated + # pc.SetLookupOptions(pa.scalar(2)) + pc.SearchSortedOptions(side="middle") # type: ignore[arg-type] + _: Hashable = options # type: ignore[assignment] # ty: ignore[invalid-assignment] # noqa: E501 + + +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(pc.list_contains([[1, 2, 3]], 1), pa.BooleanArray) + check(pc.list_contains(pa.chunked_array([[[1, 2, 3]]]), 1), pa.ChunkedArray) + check(pc.list_element([[1, 2, 3]], 1), pa.Int64Array) + check(assert_type(pc.list_flatten([[1, 2], [3]]), pa.Array | pa.ChunkedArray), + pa.Int64Array) + check(assert_type(pc.list_flatten(pa.scalar([1, 2])), pa.Array | pa.ChunkedArray), + pa.Int64Array) + check(assert_type(pc.list_parent_indices(pa.chunked_array([[[1, 2], [3]]])), + pa.Int64Array | pa.ChunkedArray), + pa.ChunkedArray) + check(pc.list_slice(pa.scalar([1, 2, 3]), 1), pa.ListScalar) + check(pc.struct_field(pa.array([{"a": 1}]), ("a",)), pa.Array) + + # Replace functions always return arrays + check(assert_type(pc.fill_null_forward([1, None]), pa.Array | pa.ChunkedArray), + pa.Int64Array) + check(assert_type(pc.fill_null_backward([None, 1]), pa.Array | pa.ChunkedArray), + pa.Int64Array) + # Replacements as an array, a scalar or a Python list + check(assert_type(pc.replace_with_mask(arr, mask, pa.array([10, 30])), + pa.Array | pa.ChunkedArray), + pa.Int64Array) + check(pc.replace_with_mask(arr, mask, pa.scalar(10)), pa.Int64Array) + check(pc.replace_with_mask(arr, mask, [10, 30]), pa.Int64Array) + + # Pairwise functions + check(assert_type(pc.pairwise_diff([1, 3, 6]), _NumericOrTemporal), pa.Int64Array) + + if TYPE_CHECKING: + pc.top_k_unstable(arr, "2") # type: ignore[arg-type] + pc.top_k_unstable([3, 1, 2], 2) # type: ignore[arg-type] + pc.sort_indices(table, [("a", "up")]) # type: ignore[list-item] + # 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] + # TODO: test invalid code once the scalar stubs are annotated + # pc.variance(range(3)), pc.round("abc") + + +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(pc.abs([1, 2]), pa.Int64Array) + check(pc.abs((1.5, -2.5)), pa.DoubleArray) + check(pc.abs(1), pa.Int64Scalar) + check(pc.abs_checked(-2.5), pa.DoubleScalar) + check(pc.add(-2.5, 1.5), pa.DoubleScalar) + check(pc.add_checked([2.5, 3.5], 1), pa.DoubleArray) + check(pc.exp(2.5), pa.DoubleScalar) + check(pc.exp([1, 2]), pa.DoubleArray) + check(pc.divide([1, 2, 3], 1), pa.Int64Array) + check(pc.divide(arr, 2.5), pa.Array) + check(pc.hypot([1, 2, 3], 1), pa.DoubleArray) + check(pc.modulo([7, -7], [3, 3]), pa.Int64Array) + check(pc.power(arr, 2), pa.Array) + check(pc.sqrt(pa.chunked_array([[1], [2, 3]])), pa.ChunkedArray) + check(pc.is_valid([1.1]), pa.BooleanArray) + check(pc.true_unless_null(1.1), pa.BooleanScalar) + + # decimal, datetime and numpy also accepted + check(pc.sqrt(Decimal("2.25")), pa.DoubleScalar) + check(pc.add(dt.datetime(2026, 1, 1), dt.timedelta(days=1)), pa.TimestampScalar) + check(pc.add(arr, np.int64(1)), pa.Int64Array) + + # Bit-wise functions + check(pc.bit_wise_and([1, 1], [1, 1]), pa.Int64Array) + check(pc.bit_wise_not([1, 1]), pa.Int64Array) + + # Rounding returns floats, or decimals for decimal input + check(pc.ceil(1.5), pa.DoubleScalar) + check(pc.floor([1, 2]), pa.DoubleArray) + check(pc.trunc(pa.scalar(Decimal("1.5"))), pa.Decimal128Scalar) + check(pc.trunc(pa.array([Decimal("1.5")])), pa.Decimal128Array) + check(pc.round((1.5, 2.5)), pa.Array) + check(pc.round([1.5, 2.5]), pa.Array) + + # Logarithms return floats + check(pc.ln(pa.array([Decimal("1.5")])), pa.DoubleArray) + + # Trigonometric functions return floats, also for decimal input + # Python lists and tuples accepted + check(pc.sin([1, 2]), pa.DoubleArray) + check(pc.acos(0.5), pa.DoubleScalar) + check(pc.atan2(1.5, [1, 2]), pa.DoubleArray) + check(pc.cosh(pa.array([Decimal("1.5")])), pa.DoubleArray) + check(pc.acos([1.1, 1.1]), pa.DoubleArray) + check(pc.atan2([1.1, 1.1], [1.1, 1.1]), pa.DoubleArray) + + # Comparisons and selections accept Python literals of any type + check(pc.equal(pa.scalar("a"), "a"), pa.BooleanScalar) + check(pc.equal(True, False), pa.BooleanScalar) + check(pc.max_element_wise(pa.array(["a", "b"]), "c"), pa.StringArray) + check(pc.less(dt.datetime(2026, 1, 1), dt.datetime(2026, 1, 2)), pa.BooleanScalar) + check(pc.greater_equal(1.1, 2.2), pa.BooleanScalar) + check(pc.if_else(True, 1, 2), pa.Int64Scalar) + selected = pc.if_else([True, False], [1, 2], [3, 4]) + check(assert_type(selected, pa.Scalar | pa.Array | pa.ChunkedArray | pc.Expression), + pa.Array) + # An Expression as the first argument gives an Expression + check(pc.if_else(pc.field("a") > 1, 1, 2), pc.Expression) + check(pc.if_else(np.bool_(True), 1, 2), pa.Int64Scalar) + check(pc.choose(1, [1, 2], [3, 4]), pa.Int64Array) + check(pc.fill_null(pa.array([1, None]), 5), pa.Int64Array) + check(pc.equal([1, 2, 1], [1, 2, 3]), pa.BooleanArray) + + check(pc.make_struct(1, 'a', field_nullability=[True]), pa.StructScalar) + check(pc.make_struct(1, 'a', field_metadata=[None]), pa.StructScalar) + cond = pc.make_struct([True, False], [False, None]) + check(pc.case_when(cond, [1, 2], [12, 13]), pa.Int64Array) + cond = pa.scalar({"a": False, "b": True}) + check(pc.case_when(cond, ["foo"], ["bar"]), pa.StringArray) + check(pc.case_when(cond, 1, 2), pa.Int64Scalar) + check(pc.case_when(cond, "a", "b"), pa.StringScalar) + check(pc.case_when([{"a": True, "b": False}], [1.1], [3.3]), pa.DoubleArray) + check(pc.choose([1, 2, 1], "a", "b", "c"), pa.StringArray) + + # Logical functions + check(pc.and_not([True], [False]), pa.BooleanArray) + + # String functions + check(pc.utf8_is_space([" "]), pa.BooleanArray) + check(pc.binary_repeat(pa.array(["a"]), (2,)), pa.Array) + check(pc.binary_repeat(b"foozfoo", [3]), pa.BinaryArray) + check(pc.replace_substring(b"foozfoo", "foo", "bar"), pa.BinaryScalar) + check(pc.ascii_ltrim(["foozfoo"], b"foo"), pa.StringArray) + check(pc.split_pattern([b"foozfoo"], b"t"), pa.ListArray) + check(pc.extract_regex(b"a1", rb"(?P[ab])(?P\d)"), + pa.StructScalar) + check(pc.binary_join([["a", "b"], ["c"]], "-"), pa.StringArray) + check(pc.binary_join(pc.field("a"), pc.field("sep")), pc.Expression) + check(pc.binary_join_element_wise(["a", "b"], ["c", "d"], "-"), pa.Array) + + # Containment tests + check(pc.count_substring([b"abcab"], "ab"), pa.Int32Array) + check(pc.ends_with([b"abcab"], "ab"), pa.BooleanArray) + check(pc.index_in([1, 2, 3], pa.array([1, 2])), pa.Int32Array) + check(pc.is_in([1, 2, 3], pa.array([1, 2])), pa.BooleanArray) + check(pc.index_in_meta_binary([1, 2, 3], [1, 2]), pa.Int32Array) + check(pc.is_in_meta_binary([1, 2, 3], [1, 2]), pa.BooleanArray) + + # Structural transforms + check(pc.list_value_length([[1], [1, 2]]), pa.Int32Array) + + # Conversions + check(pc.ceil_temporal([dt.datetime(2026, 11, 23, 10, 17)]), pa.TimestampArray) + check(pc.cast(1, pa.float32()), pa.FloatScalar) + check(pc.strftime(dt.datetime(2026, 11, 23), format="%Y-%m-%d"), pa.StringScalar) + check(pc.strftime(pc.field("ts"), format=b"%Y-%m-%d"), pc.Expression) + check(pc.strptime(["5/1/2020", None, "12/13/1900"], format='%m/%d/%Y', unit='s'), + pa.TimestampArray) + check(pc.strptime("5/1/2020", format=b'%m/%d/%Y', unit='s'), pa.TimestampScalar) + ree = pc.run_end_encode([1, 1, None, None, None, 2, 2, 3]) + check(assert_type(ree, pa.RunEndEncodedArray | pa.ChunkedArray), + pa.RunEndEncodedArray) + check(assert_type(pc.run_end_decode(ree), pa.Array | pa.ChunkedArray), pa.Array) + + # Temporal + date = dt.datetime(2026, 1, 1) + check(pc.day(date), pa.Int64Scalar) + check(pc.day([date]), pa.Int64Array) + check(pc.hour(date), pa.Int64Scalar) + check(pc.subsecond(date), pa.DoubleScalar) + check(pc.is_leap_year((date,)), pa.BooleanArray) + check(pc.days_between(date, date), pa.Int64Scalar) + check(pc.month_day_nano_interval_between([date], [date]), + pa.MonthDayNanoIntervalArray) + check(pc.years_between((date, ), (date, )), pa.Int64Array) + check(pc.assume_timezone([date], timezone=b"UTC"), pa.TimestampArray) + check(pc.local_timestamp(date), pa.TimestampScalar) + + if TYPE_CHECKING: + pc.is_in([1, 2, 3], pc.field("a")) # type: ignore[arg-type] + pc.random(3.14) # type: ignore[arg-type] + pc.make_struct(1, 'a', field_nullability=True) # type: ignore[arg-type] + # Fails when evaluated (ds.dataset(table).to_table(columns={"r": ...})): + pc.run_end_encode(pc.field("a")) # type: ignore[arg-type] + # TODO: test invalid code once the scalar stubs are annotated + # pc.bit_wise_and(1.0, 1.0), pc.bit_wise_not(1.0) + # pc.add("a", 1), pc.sqrt(dt.timedelta(days=1)), pc.if_else("yes", 1, 2) + # pc.index_in([1, 2, 3], options=pc.SetLookupOptions(pa.scalar(2))) + # pc.cast(pa.table({"a": [1]}), pa.float32()), pc.cast(pc.field("a"), "int64") + + +def test_agg_functions() -> None: + import numpy as np + + arr = pa.array([3, 1, 2]) + scalar = pa.scalar(1) + + # Scalar input accepted + check(pc.count(scalar), pa.Int64Scalar) + check(pc.count_distinct(scalar), pa.Int64Scalar) + check(pc.first(scalar), pa.Int64Scalar) + check(pc.last(scalar), pa.Int64Scalar) + check(pc.first_last(scalar), pa.StructScalar) + + # Aggregations return no expression + check(assert_type(pc.mode(arr, n=2), pa.StructArray), pa.StructArray) + + # Quantile returns doubles, or the input type for "lower", "higher", "nearest" + check(assert_type(pc.quantile(arr, q=[0.25, 0.75]), _Quantile), pa.DoubleArray) + check(assert_type(pc.quantile(arr, interpolation="lower"), _Quantile), + pa.Int64Array) + + # Python lists, tuples and NumPy arrays accepted + check(pc.variance([1, 2, 3]), pa.DoubleScalar) + check(pc.variance((1, 2, 3)), pa.DoubleScalar) + check(pc.variance(np.array([1.0, 2.0, 3.0])), pa.DoubleScalar) + check(pc.first_last((1, 2)), pa.StructScalar) + + # A Python value accepted + check(pc.index(arr, 2), pa.Int64Scalar) + + # TODO: test invalid code once the scalar stubs are annotated + # Aggregations can't be evaluated as expressions, e.g. evaluating + # pc.sum(pc.field("a")) in ds.dataset(table).to_table(columns=...) fails: + # pc.sum(pc.field("a")) diff --git a/python/pyarrow-stubs-tests/test_fs.py b/python/pyarrow-stubs-tests/test_fs.py new file mode 100644 index 00000000000..7d39439289b --- /dev/null +++ b/python/pyarrow-stubs-tests/test_fs.py @@ -0,0 +1,50 @@ +# 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 pathlib import Path +from typing import TYPE_CHECKING + +import pyarrow.fs as fs + +from _check import assert_type, check + + +def test_local_filesystem(tmp_path: Path) -> None: + local = fs.LocalFileSystem() + check(assert_type(local, fs.LocalFileSystem), fs.LocalFileSystem) + check(assert_type(local.type_name, str), str) + + info = local.get_file_info(str(tmp_path)) + check(assert_type(info, fs.FileInfo), fs.FileInfo) + check(assert_type(info.type, fs.FileType), fs.FileType) + check(assert_type(info.path, str), str) + + selector = fs.FileSelector(str(tmp_path), recursive=True) + infos = local.get_file_info(selector) + check(assert_type(infos, list[fs.FileInfo]), list) + + sub = fs.SubTreeFileSystem(str(tmp_path), local) + check(assert_type(sub, fs.SubTreeFileSystem), fs.SubTreeFileSystem) + + resolved_fs, resolved_path = fs.FileSystem.from_uri(tmp_path.as_uri()) + check(assert_type(resolved_fs, fs.FileSystem), fs.FileSystem) + check(assert_type(resolved_path, str), str) + + +def test_invalid_usage() -> None: + if TYPE_CHECKING: + fs.FileSelector(123) # 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..51d5357755c --- /dev/null +++ b/python/pyarrow-stubs-tests/test_io_formats.py @@ -0,0 +1,100 @@ +# 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 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) + + 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) + + 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_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: + pa.allocate_buffer("not an int") # type: ignore[call-overload] # ty: ignore[no-matching-overload] + pa.compress(b"abc", codec="invalid") # type: ignore[call-overload] # ty: ignore[no-matching-overload] diff --git a/python/pyarrow-stubs-tests/test_leaf_modules.py b/python/pyarrow-stubs-tests/test_leaf_modules.py new file mode 100644 index 00000000000..1eb2e63ae28 --- /dev/null +++ b/python/pyarrow-stubs-tests/test_leaf_modules.py @@ -0,0 +1,33 @@ +# 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 pyarrow as pa +import pyarrow.interchange as interchange +import pyarrow.util as pa_util + +from _check import assert_type, check + + +def test_interchange() -> None: + table = pa.table({"a": [1, 2, 3], "b": ["x", "y", "z"]}) + df_obj = table.__dataframe__() + roundtripped = interchange.from_dataframe(df_obj) + check(assert_type(roundtripped, pa.Table), pa.Table) + + +def test_util() -> None: + check(assert_type(pa_util.guid(), str), str) diff --git a/python/pyarrow-stubs-tests/test_parquet_dataset.py b/python/pyarrow-stubs-tests/test_parquet_dataset.py new file mode 100644 index 00000000000..261cb2de81f --- /dev/null +++ b/python/pyarrow-stubs-tests/test_parquet_dataset.py @@ -0,0 +1,48 @@ +# 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 pathlib import Path +from typing import TYPE_CHECKING + +import pyarrow as pa +import pyarrow.dataset as ds +import pyarrow.parquet as pq + +from _check import assert_type, check + + +def test_parquet_and_dataset(tmp_path: Path) -> None: + table = pa.table({"a": [1, 2, 3], "b": ["x", "y", "z"]}) + path = tmp_path / "data.parquet" + pq.write_table(table, path) + + read_back = pq.read_table(path) + check(assert_type(read_back, pa.Table), pa.Table) + + pf = pq.ParquetFile(path) + check(assert_type(pf.metadata, pq.FileMetaData), pq.FileMetaData) + check(assert_type(pf.num_row_groups, int), int) + check(assert_type(pf.read(), pa.Table), pa.Table) + + dset = ds.dataset(path, format="parquet") + check(assert_type(dset.schema, pa.Schema), pa.Schema) + check(assert_type(dset.to_table(), pa.Table), pa.Table) + + +def test_invalid_usage() -> None: + if TYPE_CHECKING: + ds.partitioning(flavor="invalid") # type: ignore[arg-type] diff --git a/python/pyarrow-stubs-tests/test_scalar.py b/python/pyarrow-stubs-tests/test_scalar.py new file mode 100644 index 00000000000..be4dc3bdc93 --- /dev/null +++ b/python/pyarrow-stubs-tests/test_scalar.py @@ -0,0 +1,316 @@ +# 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, Iterator, Mapping, Sequence +from decimal import Decimal +from typing import Any, cast, TYPE_CHECKING +from uuid import UUID + +import pytest +from typing_extensions import CapsuleType + +import pyarrow as pa +# Not exported from pyarrow until io.pyi is annotated +from pyarrow.lib import Buffer + +from _check import assert_type, check + + +def test_scalar() -> None: + # pa.scalar() return type is Scalar. Tell the type checker which subclass + # to expect. + s = check(assert_type(pa.scalar(1), pa.Scalar), pa.Int64Scalar) + check(assert_type(s.type, pa.DataType), pa.DataType) + check(assert_type(s.is_valid, bool), bool) + check(assert_type(s.as_py(), Any), int) + check(assert_type(s.as_py(maps_as_pydicts="strict"), Any), int) + check(assert_type(s.equals(pa.scalar(1)), bool), bool) + check(assert_type(s.cast(pa.int8()), pa.Scalar), pa.Int8Scalar) + check(assert_type(s.cast("int8", safe=None), pa.Scalar), pa.Int8Scalar) + check(assert_type(pa.scalar(1, "int8"), pa.Scalar), pa.Int8Scalar) + check(assert_type(pa.scalar(1, pa.int8(), from_pandas=True), pa.Scalar), + pa.Int8Scalar) + assert_type(s.validate(full=True), None) + # Scalars, unlike arrays, are hashable + _: Hashable = s + + check(assert_type(pa.NA, pa.NullScalar), pa.NullScalar) + check(assert_type(pa.NULL, pa.NullScalar), pa.NullScalar) + assert_type(pa.NA.as_py(), None) + + +def test_scalar_operators() -> None: + s = pa.scalar(6) + check(assert_type(-s, pa.Scalar), pa.Int64Scalar) + check(assert_type(abs(s), pa.Scalar), pa.Int64Scalar) + # The result is a scalar, or an array if the other operand is one + check(assert_type(s + 1, Any), pa.Int64Scalar) + check(assert_type(s + pa.scalar(1), Any), pa.Int64Scalar) + check(assert_type(s - pa.array([1]), Any), pa.Int64Array) + check(assert_type(s * pa.chunked_array([[1]]), Any), pa.ChunkedArray) + check(assert_type(s / 4, Any), pa.Int64Scalar) + check(assert_type(s ** 2, Any), pa.Int64Scalar) + check(assert_type(s & 3, Any), pa.Int64Scalar) + check(assert_type(s | 3, Any), pa.Int64Scalar) + check(assert_type(s ^ 3, Any), pa.Int64Scalar) + check(assert_type(s << 1, Any), pa.Int64Scalar) + check(assert_type(s >> 1, Any), pa.Int64Scalar) + + if TYPE_CHECKING: + # Scalars don't implement the reflected operators + 1 + s # type: ignore[operator] # ty: ignore[unsupported-operator] + # nor floor division and modulo + s // 2 # type: ignore[operator] # ty: ignore[unsupported-operator] + s % 2 # type: ignore[operator] # ty: ignore[unsupported-operator] + + +def test_array_items() -> None: + arr = cast(pa.Int64Array, pa.array([1, 2])) + check(assert_type(arr[0], pa.Scalar), pa.Int64Scalar) + check(assert_type(next(iter(arr)), pa.Scalar), pa.Int64Scalar) + check(assert_type(arr.sum(), pa.Scalar), pa.Int64Scalar) + check(assert_type(arr.index(2), pa.Int64Scalar), pa.Int64Scalar) + check(assert_type(pa.chunked_array([arr]).index(2), pa.Int64Scalar), + pa.Int64Scalar) + + +def test_primitive_scalars() -> None: + boolean = cast(pa.BooleanScalar, pa.scalar(True)) + check(assert_type(boolean.as_py(), bool | None), bool) + check(assert_type(bool(boolean), bool), bool) + + integer = cast(pa.Int8Scalar, pa.scalar(1, pa.int8())) + check(assert_type(integer.as_py(), int | None), int) + # Integer scalars can be used as indices + check(assert_type([1, 2][integer], int), int) + + double = cast(pa.DoubleScalar, pa.scalar(1.5)) + check(assert_type(double.as_py(), float | None), float) + check(float(double), float) + check(assert_type(int(double), int), int) + + decimal = cast(pa.Decimal128Scalar, pa.scalar(Decimal("1.5"))) + check(assert_type(decimal.as_py(), Decimal | None), Decimal) + + null_int = cast(pa.Int64Scalar, pa.scalar(None, pa.int64())) + assert_type(null_int.as_py(), int | None) + assert null_int.as_py() is None + + +def test_temporal_scalars() -> None: + date = cast(pa.Date32Scalar, pa.scalar(dt.date(2020, 1, 1))) + check(assert_type(date.value, int | None), int) + check(assert_type(date.as_py(), dt.date | None), dt.date) + + date64 = cast(pa.Date64Scalar, pa.scalar(dt.date(2020, 1, 1), pa.date64())) + check(assert_type(date64.value, int | None), int) + check(assert_type(date64.as_py(), dt.date | None), dt.date) + + time = cast(pa.Time64Scalar, pa.scalar(dt.time(1, 2))) + check(assert_type(time.value, int | None), int) + check(assert_type(time.as_py(), dt.time | None), dt.time) + + time32 = cast(pa.Time32Scalar, pa.scalar(dt.time(1, 2), pa.time32("s"))) + check(assert_type(time32.as_py(), dt.time | None), dt.time) + + timestamp = cast(pa.TimestampScalar, pa.scalar(dt.datetime(2020, 1, 1))) + check(assert_type(timestamp.value, int | None), int) + check(assert_type(timestamp.as_py(), dt.datetime | None), dt.datetime) + + duration = cast(pa.DurationScalar, pa.scalar(dt.timedelta(seconds=1))) + check(assert_type(duration.value, int | None), int) + check(assert_type(duration.as_py(), dt.timedelta | None), dt.timedelta) + + interval = cast(pa.MonthDayNanoIntervalScalar, + pa.scalar(pa.MonthDayNano([1, 2, 3]))) + check(assert_type(interval.value, pa.MonthDayNano | None), pa.MonthDayNano) + check(assert_type(interval.as_py(), pa.MonthDayNano | None), + pa.MonthDayNano) + + +def test_binary_scalars() -> None: + binary = cast(pa.BinaryScalar, pa.scalar(b"abc")) + check(assert_type(binary.as_py(), bytes | None), bytes) + check(assert_type(binary.as_buffer(), Buffer | None), pa.Buffer) + check(assert_type(bytes(binary), bytes), bytes) + check(assert_type(memoryview(binary), memoryview), memoryview) + + # String scalars are binary scalars at runtime + string = cast(pa.StringScalar, pa.scalar("abc")) + check(assert_type(string.as_py(), str | None), str) + check(assert_type(string.as_buffer(), Buffer | None), pa.Buffer) + check(string, pa.BinaryScalar) + + large = cast(pa.LargeStringScalar, pa.scalar("abc", pa.large_string())) + check(assert_type(large.as_py(), str | None), str) + view = cast(pa.BinaryViewScalar, pa.scalar(b"abc", pa.binary_view())) + check(assert_type(view.as_py(), bytes | None), bytes) + + +def test_list_scalar() -> None: + lst = cast(pa.ListScalar, pa.scalar([1, 2])) + check(assert_type(lst.values, pa.Array | None), pa.Int64Array) + check(assert_type(len(lst), int), int) + check(assert_type(lst[0], pa.Scalar), pa.Int64Scalar) + check(assert_type(next(iter(lst)), pa.Scalar), pa.Int64Scalar) + check(assert_type(lst.as_py(), list[Any] | None), list) + # List scalars are sequences at runtime + seq: Sequence[pa.Scalar] = check(lst, Sequence) + check(assert_type(seq.index(lst[1]), int), int) + + fixed = cast(pa.FixedSizeListScalar, + pa.scalar([1, 2], pa.list_(pa.int64(), 2))) + check(assert_type(fixed[0], pa.Scalar), pa.Int64Scalar) + + null_list = cast(pa.ListScalar, pa.scalar(None, pa.list_(pa.int64()))) + assert_type(null_list.values, pa.Array | None) + assert null_list.values is None + assert null_list.as_py() is None + + if TYPE_CHECKING: + # Only integer indices are supported, not slices + lst[1:] # type: ignore[index] + + +def test_struct_scalar() -> None: + struct = cast(pa.StructScalar, pa.scalar({"a": 1, "b": "x"})) + check(assert_type(struct["a"], pa.Scalar), pa.Int64Scalar) + check(assert_type(struct[1], pa.Scalar), pa.StringScalar) + check(assert_type(len(struct), int), int) + check(assert_type("a" in struct, bool), bool) + check(assert_type(list(struct), list[str]), list) + check(assert_type(struct.items(), Iterator[tuple[str, pa.Scalar]]), Iterator) + check(assert_type(struct.as_py(), dict[str, Any] | None), dict) + # Struct scalars are mappings at runtime + mapping: Mapping[str, pa.Scalar] = check(struct, Mapping) + check(assert_type(mapping.get("a"), pa.Scalar | None), pa.Int64Scalar) + + +def test_map_scalar() -> None: + map_type = pa.map_(pa.string(), pa.int64()) + map_scalar = cast(pa.MapScalar, pa.scalar([("a", 1)], map_type)) + check(map_scalar, pa.ListScalar) + check(assert_type(map_scalar.values, pa.Array | None), pa.StructArray) + check(assert_type(map_scalar[0], tuple[pa.Scalar, pa.Scalar]), tuple) + check(assert_type(map_scalar["a"], pa.Scalar), pa.Int64Scalar) + check(assert_type(map_scalar.keys(), list[Any]), list) + # Iterating yields the (key, item) pairs as Python objects + check(assert_type(next(iter(map_scalar)), tuple[Any, Any]), tuple) + # as_py() returns a list of pairs, or a dict if maps_as_pydicts is given + check(assert_type(map_scalar.as_py(), list[tuple[Any, Any]] | None), list) + check(assert_type(map_scalar.as_py(maps_as_pydicts="lossy"), + dict[Any, Any] | None), + dict) + + null_map = cast(pa.MapScalar, pa.scalar(None, map_type)) + assert null_map.as_py() is None + assert null_map.as_py(maps_as_pydicts="strict") is None + check(assert_type(null_map.keys(), list[Any]), list) + + +def test_dictionary_scalar() -> None: + dict_arr = pa.array(["a", "b"]).dictionary_encode() + dict_scalar = cast(pa.DictionaryScalar, dict_arr[1]) + index = check(dict_scalar.index, pa.Int32Scalar) + # The index type is one of the integer types + check(assert_type(index.as_py(), int | None), int) + check(assert_type(dict_scalar.value, pa.Scalar), pa.StringScalar) + check(assert_type(dict_scalar.dictionary, pa.Array), pa.StringArray) + + +def test_run_end_encoded_scalar() -> None: + ree = pa.RunEndEncodedArray.from_arrays([2], ["a"]) + ree_scalar = cast(pa.RunEndEncodedScalar, ree[0]) + check(assert_type(ree_scalar.value, pa.Scalar), pa.StringScalar) + + +def test_union_scalar() -> None: + union = pa.UnionArray.from_sparse( + cast(pa.Int8Array, pa.array([0], pa.int8())), [pa.array([1])] + ) + union_scalar = cast(pa.UnionScalar, union[0]) + check(assert_type(union_scalar.value, pa.Scalar | None), pa.Int64Scalar) + check(assert_type(union_scalar.type_code, int), int) + + null_union = pa.UnionArray.from_sparse( + cast(pa.Int8Array, pa.array([0], pa.int8())), + [pa.array([None], pa.int64())], + ) + null_scalar = cast(pa.UnionScalar, null_union[0]) + assert_type(null_scalar.value, pa.Scalar | None) + assert null_scalar.value is None + + +def test_extension_scalars() -> None: + ext = pa.ExtensionScalar.from_storage(pa.uuid(), b"0" * 16) + uuid = check(assert_type(ext, pa.ExtensionScalar), pa.UuidScalar) + check(assert_type(uuid.value, pa.Scalar | None), pa.FixedSizeBinaryScalar) + + uuid_scalar = cast(pa.UuidScalar, uuid) + check(assert_type(uuid_scalar.as_py(), UUID | None), UUID) + + null_uuid = cast(pa.UuidScalar, + pa.ExtensionScalar.from_storage(pa.uuid(), None)) + assert null_uuid.value is None + assert null_uuid.as_py() is None + + bool8 = cast(pa.Bool8Scalar, pa.scalar(1, pa.bool8())) + check(assert_type(bool8.as_py(), bool | None), bool) + + +def test_scalar_numpy_index() -> None: + pytest.importorskip("numpy") + import numpy as np + + # Anything with __index__ can index a list or map scalar, e.g. NumPy ints + lst = cast(pa.ListScalar, pa.scalar([1, 2])) + check(assert_type(lst[np.int64(0)], pa.Scalar), pa.Int64Scalar) + map_scalar = cast(pa.MapScalar, + pa.scalar([("a", 1)], pa.map_(pa.string(), pa.int64()))) + check(assert_type(map_scalar[np.int64(0)], tuple[pa.Scalar, pa.Scalar]), + tuple) + if TYPE_CHECKING: + # Struct scalars only take int positions + struct = cast(pa.StructScalar, pa.scalar({"a": 1})) + struct[np.int64(0)] # type: ignore[index] + + +def test_fixed_shape_tensor_scalar() -> None: + pytest.importorskip("numpy") + import numpy as np + + tensor_type = pa.fixed_shape_tensor(pa.int32(), [2]) + storage = pa.array([[1, 2]], pa.list_(pa.int32(), 2)) + tensors = cast(pa.FixedShapeTensorArray, tensor_type.wrap_array(storage)) + tensor = cast(pa.FixedShapeTensorScalar, tensors[0]) + check(assert_type(tensor.to_numpy(), np.ndarray), np.ndarray) + check(assert_type(tensor.to_tensor(), pa.Tensor), pa.Tensor) + check(assert_type(tensor.__dlpack_device__(), tuple[int, int]), tuple) + check(assert_type(tensor.__dlpack__(max_version=(1, 0)), CapsuleType), + CapsuleType) + + +def test_invalid_usage() -> None: + s = pa.scalar(1) + if TYPE_CHECKING: + s.equals(1) # type: ignore[arg-type] + s.cast(1) # type: ignore[arg-type] + s.as_py(maps_as_pydicts="loose") # type: ignore[arg-type] + pa.scalar(1, type=1) # type: ignore[arg-type] + # Scalars don't have the methods of their subclasses + s.value # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] diff --git a/python/pyarrow-stubs/__init__.pyi b/python/pyarrow-stubs/__init__.pyi index 445936bef98..a3fc1549be3 100644 --- a/python/pyarrow-stubs/__init__.pyi +++ b/python/pyarrow-stubs/__init__.pyi @@ -15,11 +15,6 @@ # specific language governing permissions and limitations # under the License. -from typing import Any - -# The names that pyarrow/__init__.py imports from pyarrow.lib and that have -# stubs already. Type checkers only fall back to __getattr__ below for the -# names that aren't defined here. from pyarrow.lib import ( Array as Array, ArrowCancelled as ArrowCancelled, @@ -35,79 +30,133 @@ from pyarrow.lib import ( ArrowTypeError as ArrowTypeError, BaseExtensionType as BaseExtensionType, BinaryArray as BinaryArray, + BinaryScalar as BinaryScalar, BinaryViewArray as BinaryViewArray, + BinaryViewScalar as BinaryViewScalar, Bool8Array as Bool8Array, + Bool8Scalar as Bool8Scalar, 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, + Date32Scalar as Date32Scalar, Date64Array as Date64Array, + Date64Scalar as Date64Scalar, Decimal128Array as Decimal128Array, + Decimal128Scalar as Decimal128Scalar, Decimal128Type as Decimal128Type, Decimal256Array as Decimal256Array, + Decimal256Scalar as Decimal256Scalar, Decimal256Type as Decimal256Type, Decimal32Array as Decimal32Array, + Decimal32Scalar as Decimal32Scalar, Decimal32Type as Decimal32Type, Decimal64Array as Decimal64Array, + Decimal64Scalar as Decimal64Scalar, Decimal64Type as Decimal64Type, DenseUnionType as DenseUnionType, Device as Device, DeviceAllocationType as DeviceAllocationType, DictionaryArray as DictionaryArray, DictionaryMemo as DictionaryMemo, + DictionaryScalar as DictionaryScalar, DictionaryType as DictionaryType, DoubleArray as DoubleArray, + DoubleScalar as DoubleScalar, DurationArray as DurationArray, + DurationScalar as DurationScalar, DurationType as DurationType, ExtensionArray as ExtensionArray, + ExtensionScalar as ExtensionScalar, ExtensionType as ExtensionType, Field as Field, FixedShapeTensorArray as FixedShapeTensorArray, + FixedShapeTensorScalar as FixedShapeTensorScalar, FixedShapeTensorType as FixedShapeTensorType, FixedSizeBinaryArray as FixedSizeBinaryArray, + FixedSizeBinaryScalar as FixedSizeBinaryScalar, FixedSizeBinaryType as FixedSizeBinaryType, + FixedSizeBufferWriter as FixedSizeBufferWriter, FixedSizeListArray as FixedSizeListArray, + FixedSizeListScalar as FixedSizeListScalar, FixedSizeListType as FixedSizeListType, FloatArray as FloatArray, + FloatScalar as FloatScalar, FloatingPointArray as FloatingPointArray, HalfFloatArray as HalfFloatArray, + HalfFloatScalar as HalfFloatScalar, Int16Array as Int16Array, + Int16Scalar as Int16Scalar, Int32Array as Int32Array, + Int32Scalar as Int32Scalar, Int64Array as Int64Array, + Int64Scalar as Int64Scalar, Int8Array as Int8Array, + Int8Scalar as Int8Scalar, IntegerArray as IntegerArray, JsonArray as JsonArray, + JsonScalar as JsonScalar, JsonType as JsonType, KeyValueMetadata as KeyValueMetadata, LargeBinaryArray as LargeBinaryArray, + LargeBinaryScalar as LargeBinaryScalar, LargeListArray as LargeListArray, + LargeListScalar as LargeListScalar, LargeListType as LargeListType, LargeListViewArray as LargeListViewArray, + LargeListViewScalar as LargeListViewScalar, LargeListViewType as LargeListViewType, LargeStringArray as LargeStringArray, + LargeStringScalar as LargeStringScalar, ListArray as ListArray, + ListScalar as ListScalar, ListType as ListType, ListViewArray as ListViewArray, + ListViewScalar as ListViewScalar, ListViewType as ListViewType, LoggingMemoryPool as LoggingMemoryPool, MapArray as MapArray, + MapScalar as MapScalar, MapType as MapType, MemoryManager as MemoryManager, + MemoryMappedFile as MemoryMappedFile, MemoryPool as MemoryPool, + MockOutputStream as MockOutputStream, MonthDayNano as MonthDayNano, MonthDayNanoIntervalArray as MonthDayNanoIntervalArray, + MonthDayNanoIntervalScalar as MonthDayNanoIntervalScalar, + 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, RuntimeInfo as RuntimeInfo, + Scalar as Scalar, Schema as Schema, SparseCOOTensor as SparseCOOTensor, SparseCSCMatrix as SparseCSCMatrix, @@ -115,28 +164,43 @@ from pyarrow.lib import ( SparseCSRMatrix as SparseCSRMatrix, SparseUnionType as SparseUnionType, StringArray as StringArray, + StringScalar as StringScalar, StringViewArray as StringViewArray, + StringViewScalar as StringViewScalar, StructArray as StructArray, + StructScalar as StructScalar, StructType as StructType, Table as Table, TableGroupBy as TableGroupBy, Tensor as Tensor, Time32Array as Time32Array, + Time32Scalar as Time32Scalar, Time32Type as Time32Type, Time64Array as Time64Array, + Time64Scalar as Time64Scalar, Time64Type as Time64Type, TimestampArray as TimestampArray, + TimestampScalar as TimestampScalar, TimestampType as TimestampType, + TransformInputStream as TransformInputStream, UInt16Array as UInt16Array, + UInt16Scalar as UInt16Scalar, UInt32Array as UInt32Array, + UInt32Scalar as UInt32Scalar, UInt64Array as UInt64Array, + UInt64Scalar as UInt64Scalar, UInt8Array as UInt8Array, + UInt8Scalar as UInt8Scalar, UnionArray as UnionArray, + UnionScalar as UnionScalar, UnionType as UnionType, UnknownExtensionType as UnknownExtensionType, UuidArray as UuidArray, + UuidScalar as UuidScalar, UuidType as UuidType, VersionInfo as VersionInfo, + allocate_buffer as allocate_buffer, + arange as arange, array as array, binary as binary, binary_view as binary_view, @@ -144,18 +208,22 @@ 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, + cpu_count as cpu_count, + create_memory_map as create_memory_map, date32 as date32, date64 as date64, decimal128 as decimal128, 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, @@ -167,12 +235,16 @@ 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, + is_opentelemetry_enabled as is_opentelemetry_enabled, jemalloc_memory_pool as jemalloc_memory_pool, jemalloc_set_decay_ms as jemalloc_set_decay_ms, json_ as json_, @@ -186,18 +258,24 @@ 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, 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, run_end_encoded as run_end_encoded, runtime_info as runtime_info, + scalar as scalar, schema as schema, + set_cpu_count as set_cpu_count, + 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, @@ -211,6 +289,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, @@ -223,9 +302,28 @@ 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 +__version__: str | None -# TODO(GH-48970): remove __getattr__ before release as this -# will annotate non-existing attributes as Any. -# https://github.com/apache/arrow/issues/48970 -def __getattr__(name: str) -> Any: ... +def show_versions() -> None: ... +def show_info() -> None: ... +def have_libhdfs() -> bool: ... +def get_include() -> str: ... +def get_libraries() -> list[str]: ... +def create_library_symlinks() -> None: ... +def get_library_dirs() -> list[str]: ... diff --git a/python/pyarrow-stubs/__lib/array.pyi b/python/pyarrow-stubs/__lib/array.pyi index d8f97ec67b1..83f4f967702 100644 --- a/python/pyarrow-stubs/__lib/array.pyi +++ b/python/pyarrow-stubs/__lib/array.pyi @@ -32,9 +32,6 @@ import numpy as np import pandas as pd from numpy.typing import NDArray -# Placeholders (Any) until scalar.pyi is annotated; mypy rejects them as -# types when imported through pyarrow.lib. -from pyarrow.__lib.scalar import Int64Scalar, Scalar from pyarrow._compute import CastOptions from pyarrow._stubs_typing import ( Indices, @@ -56,8 +53,10 @@ from pyarrow.lib import ( Device, DeviceAllocationType, Field, + Int64Scalar, MemoryManager, MemoryPool, + Scalar, Tensor, _Weakrefable, ) @@ -84,14 +83,19 @@ def array( memory_pool: MemoryPool | None = None, ) -> Array: ... @overload -def asarray( # type: ignore[overload-overlap] - values: ChunkedArray, type: Any | None = None -) -> ChunkedArray: ... +def asarray(values: ChunkedArray, type: Any | None = None) -> ChunkedArray: ... @overload def asarray( values: _ArrayConstructorInput, type: Any | None = None, ) -> Array: ... +def arange( + start: int, + stop: int, + step: int = 1, + *, + memory_pool: MemoryPool | None = None, +) -> Int64Array: ... def nulls( size: int, type: Any | None = None, @@ -625,6 +629,7 @@ def concat_arrays( def _empty_array(type: DataType) -> Array: ... __all__ = [ + "arange", "array", "asarray", "nulls", diff --git a/python/pyarrow-stubs/__lib/compat.pyi b/python/pyarrow-stubs/__lib/compat.pyi new file mode 100644 index 00000000000..8b720e87ea2 --- /dev/null +++ b/python/pyarrow-stubs/__lib/compat.pyi @@ -0,0 +1,22 @@ +# 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. + +def encode_file_path(path: str | bytes) -> bytes: ... +def tobytes(o: str | bytes) -> bytes: ... +def frombytes(o: bytes, *, safe: bool = False) -> str: ... + +__all__ = ["encode_file_path", "tobytes", "frombytes"] diff --git a/python/pyarrow-stubs/__lib/io.pyi b/python/pyarrow-stubs/__lib/io.pyi index 8a1da39a1cf..1628b781e2c 100644 --- a/python/pyarrow-stubs/__lib/io.pyi +++ b/python/pyarrow-stubs/__lib/io.pyi @@ -15,11 +15,392 @@ # 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 +from pyarrow._stubs_typing import Compression, SupportPyBuffer +from pyarrow.lib import ( + Device, + DeviceAllocationType, + KeyValueMetadata, + MemoryManager, + MemoryPool, + _Weakrefable, +) -class Buffer: ... +def have_libhdfs() -> bool: ... +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]) -> None: ... + def download( + self, stream_or_path: StrPath | IOBase, buffer_size: int | None = None + ) -> None: ... + def upload(self, stream: IOBase, 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 _open( + self, path: str, mode: Literal["r", "rb", "w", "wb", "r+", "r+b", "rb+"] = "r" + ) -> None: ... + def resize(self, new_size: int) -> None: ... + +def memory_map( + path: str, mode: Literal["r", "rb", "w", "wb", "r+", "r+b", "rb+"] = "r" +) -> MemoryMappedFile: ... + +create_memory_map = MemoryMappedFile.create + +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: ... + def _assert_cpu(self) -> None: ... + @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, /) -> Self: ... + @overload + def __getitem__(self, key: int, /) -> int: ... + def slice(self, offset: int = 0, length: int | None = None) -> Self: ... + def equals(self, other: Buffer) -> bool: ... + def __reduce_ex__(self, protocol: SupportsIndex) -> str | 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[False] = False +) -> Buffer: ... +@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], Any] + ) -> None: ... + +class Transcoder: + def __init__(self, decoder: Any, encoder: Any) -> None: ... + def __call__(self, buf: Buffer) -> bytes: ... + +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: Any | 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 = True, + prefetch_limit: int = 0, + ) -> 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) -> int: ... + @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__ = [ + "have_libhdfs", + "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", + "Transcoder", + "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/pandas_shim.pyi b/python/pyarrow-stubs/__lib/pandas_shim.pyi new file mode 100644 index 00000000000..c95e994cf9b --- /dev/null +++ b/python/pyarrow-stubs/__lib/pandas_shim.pyi @@ -0,0 +1,70 @@ +# 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 types as stdlib_types +from collections.abc import Iterable +from typing import Any, TypeGuard + +from pandas import Categorical, DatetimeTZDtype, Index, Series, DataFrame + +from numpy import dtype +from pandas.core.dtypes.base import ExtensionDtype + +class _PandasAPIShim: + has_sparse: bool + + def series(self, *args: Any, **kwargs: Any) -> Series: ... + def data_frame(self, *args: Any, **kwargs: Any) -> DataFrame: ... + @property + def have_pandas(self) -> bool: ... + @property + def compat(self) -> stdlib_types.ModuleType: ... + @property + def pd(self) -> stdlib_types.ModuleType: ... + def infer_dtype(self, obj: Iterable[Any]) -> str: ... + def pandas_dtype(self, dtype: str) -> dtype: ... + @property + def loose_version(self) -> Any: ... + @property + def version(self) -> str: ... + def is_v1(self) -> bool: ... + def is_ge_v21(self) -> bool: ... + def is_ge_v23(self) -> bool: ... + def is_ge_v3(self) -> bool: ... + def uses_string_dtype(self) -> bool: ... + @property + def categorical_type(self) -> type[Categorical]: ... + @property + def datetimetz_type(self) -> type[DatetimeTZDtype]: ... + @property + def extension_dtype(self) -> type[ExtensionDtype]: ... + def is_array_like( + self, obj: Any + ) -> TypeGuard[Series | Index | Categorical | ExtensionDtype]: ... + def is_categorical(self, obj: Any) -> TypeGuard[Categorical]: ... + def is_datetimetz(self, obj: Any) -> TypeGuard[DatetimeTZDtype]: ... + def is_extension_array_dtype(self, obj: Any) -> TypeGuard[ExtensionDtype]: ... + def is_sparse(self, obj: Any) -> bool: ... + def is_data_frame(self, obj: Any) -> TypeGuard[DataFrame]: ... + def is_series(self, obj: Any) -> TypeGuard[Series]: ... + def is_index(self, obj: Any) -> TypeGuard[Index]: ... + def get_values(self, obj: Any) -> bool: ... + def get_rangeindex_attribute(self, level: Any, name: str) -> Any: ... + +_pandas_api: _PandasAPIShim + +__all__ = ["_PandasAPIShim", "_pandas_api"] diff --git a/python/pyarrow-stubs/__lib/scalar.pyi b/python/pyarrow-stubs/__lib/scalar.pyi index 307b3e689a2..be4a40d9943 100644 --- a/python/pyarrow-stubs/__lib/scalar.pyi +++ b/python/pyarrow-stubs/__lib/scalar.pyi @@ -15,11 +15,378 @@ # 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 datetime as dt +from collections.abc import Iterator, Mapping, Sequence +from decimal import Decimal +from typing import Any, SupportsIndex, TypeAlias, overload +from uuid import UUID -from typing import Any +import numpy as np +from pyarrow._compute import CastOptions +from pyarrow._stubs_typing import MapsAsPydicts +from pyarrow.lib import ( + Array, + BaseExtensionType, + Buffer, + DataType, + MemoryPool, + MonthDayNano, + Tensor, + _Weakrefable, +) +from typing_extensions import CapsuleType -class ExtensionScalar: ... +class Scalar(_Weakrefable): + @property + def type(self) -> DataType: ... + @property + def is_valid(self) -> bool: ... + def cast( + self, + target_type: DataType | str | None = None, + safe: bool | None = None, + options: CastOptions | None = None, + memory_pool: MemoryPool | None = None, + ) -> Scalar: ... + def validate(self, *, full: bool = False) -> None: ... + def equals(self, other: Scalar) -> bool: ... + def as_py(self, *, maps_as_pydicts: MapsAsPydicts | None = None) -> Any: ... + def __abs__(self) -> Scalar: ... + def __neg__(self) -> Scalar: ... + # The binary operators call the compute functions, which return a scalar, + # or an (chunked) array if the other operand is one. + def __add__(self, other: Any, /) -> Any: ... + def __sub__(self, other: Any, /) -> Any: ... + def __mul__(self, other: Any, /) -> Any: ... + def __truediv__(self, other: Any, /) -> Any: ... + def __pow__(self, other: Any, mod: None = None, /) -> Any: ... + def __and__(self, other: Any, /) -> Any: ... + def __or__(self, other: Any, /) -> Any: ... + def __xor__(self, other: Any, /) -> Any: ... + def __lshift__(self, other: Any, /) -> Any: ... + def __rshift__(self, other: Any, /) -> Any: ... -def __getattr__(name: str) -> Any: ... +class NullScalar(Scalar): + def as_py(self, *, maps_as_pydicts: MapsAsPydicts | None = None) -> None: ... + +NA: NullScalar +_NULL: NullScalar + +class BooleanScalar(Scalar): + def as_py(self, *, maps_as_pydicts: MapsAsPydicts | None = None) -> bool | None: ... + def __bool__(self) -> bool: ... + +class UInt8Scalar(Scalar): + def as_py(self, *, maps_as_pydicts: MapsAsPydicts | None = None) -> int | None: ... + def __index__(self) -> int: ... + +class Int8Scalar(Scalar): + def as_py(self, *, maps_as_pydicts: MapsAsPydicts | None = None) -> int | None: ... + def __index__(self) -> int: ... + +class UInt16Scalar(Scalar): + def as_py(self, *, maps_as_pydicts: MapsAsPydicts | None = None) -> int | None: ... + def __index__(self) -> int: ... + +class Int16Scalar(Scalar): + def as_py(self, *, maps_as_pydicts: MapsAsPydicts | None = None) -> int | None: ... + def __index__(self) -> int: ... + +class UInt32Scalar(Scalar): + def as_py(self, *, maps_as_pydicts: MapsAsPydicts | None = None) -> int | None: ... + def __index__(self) -> int: ... + +class Int32Scalar(Scalar): + def as_py(self, *, maps_as_pydicts: MapsAsPydicts | None = None) -> int | None: ... + def __index__(self) -> int: ... + +class UInt64Scalar(Scalar): + def as_py(self, *, maps_as_pydicts: MapsAsPydicts | None = None) -> int | None: ... + def __index__(self) -> int: ... + +class Int64Scalar(Scalar): + def as_py(self, *, maps_as_pydicts: MapsAsPydicts | None = None) -> int | None: ... + def __index__(self) -> int: ... + +_IntegerScalar: TypeAlias = ( + UInt8Scalar + | Int8Scalar + | UInt16Scalar + | Int16Scalar + | UInt32Scalar + | Int32Scalar + | UInt64Scalar + | Int64Scalar +) + +class HalfFloatScalar(Scalar): + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> float | None: ... + def __float__(self) -> float: ... + def __int__(self) -> int: ... + +class FloatScalar(Scalar): + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> float | None: ... + def __float__(self) -> float: ... + def __int__(self) -> int: ... + +class DoubleScalar(Scalar): + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> float | None: ... + def __float__(self) -> float: ... + def __int__(self) -> int: ... + +class Decimal32Scalar(Scalar): + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> Decimal | None: ... + +class Decimal64Scalar(Scalar): + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> Decimal | None: ... + +class Decimal128Scalar(Scalar): + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> Decimal | None: ... + +class Decimal256Scalar(Scalar): + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> Decimal | None: ... + +# The value properties of the temporal scalars hold the integer stored in the +# array (e.g. days since the epoch for Date32Scalar), as_py() converts it. +class Date32Scalar(Scalar): + @property + def value(self) -> int | None: ... + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> dt.date | None: ... + +class Date64Scalar(Scalar): + @property + def value(self) -> int | None: ... + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> dt.date | None: ... + +class Time32Scalar(Scalar): + @property + def value(self) -> int | None: ... + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> dt.time | None: ... + +class Time64Scalar(Scalar): + @property + def value(self) -> int | None: ... + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> dt.time | None: ... + +class TimestampScalar(Scalar): + @property + def value(self) -> int | None: ... + # A pandas.Timestamp, a datetime subclass, for nanoseconds if pandas is + # installed. + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> dt.datetime | None: ... + +class DurationScalar(Scalar): + @property + def value(self) -> int | None: ... + # A pandas.Timedelta, a timedelta subclass, for nanoseconds if pandas is + # installed. + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> dt.timedelta | None: ... + +class MonthDayNanoIntervalScalar(Scalar): + @property + def value(self) -> MonthDayNano | None: ... + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> MonthDayNano | None: ... + +class BinaryScalar(Scalar): + def as_buffer(self) -> Buffer | None: ... + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> bytes | None: ... + def __bytes__(self) -> bytes: ... + # Scalars support the buffer protocol on every Python version, but only + # have a __buffer__ method at runtime from Python 3.12 on. + def __buffer__(self, flags: int, /) -> memoryview: ... + +class LargeBinaryScalar(BinaryScalar): ... +class FixedSizeBinaryScalar(BinaryScalar): ... +class BinaryViewScalar(BinaryScalar): ... + +class StringScalar(BinaryScalar): + def as_py( # type: ignore[override] + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> str | None: ... + +class LargeStringScalar(StringScalar): ... +class StringViewScalar(StringScalar): ... + +class ListScalar(Scalar, Sequence[Scalar]): + @property + 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 __iter__(self) -> Iterator[Scalar]: ... + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> list[Any] | None: ... + +class FixedSizeListScalar(ListScalar): ... +class LargeListScalar(ListScalar): ... +class ListViewScalar(ListScalar): ... +class LargeListViewScalar(ListScalar): ... + +class StructScalar(Scalar, Mapping[str, Scalar]): + def __len__(self) -> int: ... + 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: ... + # The runtime yields a generator instead of a Mapping view + def items(self) -> Iterator[tuple[str, Scalar]]: ... # type: ignore[override] + def as_py( + self, *, maps_as_pydicts: MapsAsPydicts | None = None + ) -> dict[str, Any] | None: ... + +# A MapScalar is a list of key-item structs. Unlike a ListScalar, it iterates +# over the (key, item) pairs as Python objects, and can be indexed by key. +class MapScalar(ListScalar): + @overload # type: ignore[override] + def __getitem__(self, i: SupportsIndex) -> tuple[Scalar, Scalar]: ... + @overload + 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. + @overload # type: ignore[override] + def as_py( + self, *, maps_as_pydicts: None = None + ) -> list[tuple[Any, Any]] | None: ... + @overload + def as_py(self, *, maps_as_pydicts: MapsAsPydicts) -> dict[Any, Any] | None: ... + +class DictionaryScalar(Scalar): + @property + def index(self) -> _IntegerScalar: ... + @property + def value(self) -> Scalar: ... + @property + def dictionary(self) -> Array: ... + +class RunEndEncodedScalar(Scalar): + @property + def value(self) -> Scalar: ... + +class UnionScalar(Scalar): + @property + def value(self) -> Scalar | None: ... + @property + def type_code(self) -> int: ... + +class ExtensionScalar(Scalar): + @property + def value(self) -> Scalar | None: ... + @staticmethod + def from_storage(typ: BaseExtensionType, value: Any) -> ExtensionScalar: ... + +class JsonScalar(ExtensionScalar): ... + +class UuidScalar(ExtensionScalar): + def as_py(self, *, maps_as_pydicts: MapsAsPydicts | None = None) -> UUID | None: ... + +class FixedShapeTensorScalar(ExtensionScalar): + def to_numpy(self) -> np.ndarray: ... + def to_tensor(self) -> Tensor: ... + def __dlpack__( + self, + *, + stream: int | None = None, + max_version: tuple[int, int] | None = None, + dl_device: tuple[int, int] | None = None, + copy: bool | None = None, + ) -> CapsuleType: ... + def __dlpack_device__(self) -> tuple[int, int]: ... + +class OpaqueScalar(ExtensionScalar): ... + +class Bool8Scalar(ExtensionScalar): + def as_py(self, *, maps_as_pydicts: MapsAsPydicts | None = None) -> bool | None: ... + +def scalar( + value: Any, + type: DataType | str | None = None, + *, + from_pandas: bool | None = None, + memory_pool: MemoryPool | None = None, +) -> Scalar: ... + +__all__ = [ + "Scalar", + "NullScalar", + "NA", + "_NULL", + "BooleanScalar", + "UInt8Scalar", + "Int8Scalar", + "UInt16Scalar", + "Int16Scalar", + "UInt32Scalar", + "Int32Scalar", + "UInt64Scalar", + "Int64Scalar", + "HalfFloatScalar", + "FloatScalar", + "DoubleScalar", + "Decimal32Scalar", + "Decimal64Scalar", + "Decimal128Scalar", + "Decimal256Scalar", + "Date32Scalar", + "Date64Scalar", + "Time32Scalar", + "Time64Scalar", + "TimestampScalar", + "DurationScalar", + "MonthDayNanoIntervalScalar", + "BinaryScalar", + "LargeBinaryScalar", + "FixedSizeBinaryScalar", + "BinaryViewScalar", + "StringScalar", + "LargeStringScalar", + "StringViewScalar", + "ListScalar", + "FixedSizeListScalar", + "LargeListScalar", + "ListViewScalar", + "LargeListViewScalar", + "StructScalar", + "MapScalar", + "DictionaryScalar", + "RunEndEncodedScalar", + "UnionScalar", + "ExtensionScalar", + "JsonScalar", + "UuidScalar", + "FixedShapeTensorScalar", + "OpaqueScalar", + "Bool8Scalar", + "scalar", +] diff --git a/python/pyarrow-stubs/__lib/table.pyi b/python/pyarrow-stubs/__lib/table.pyi index 126a81ce04e..7b5e51fa7ae 100644 --- a/python/pyarrow-stubs/__lib/table.pyi +++ b/python/pyarrow-stubs/__lib/table.pyi @@ -33,10 +33,9 @@ import numpy as np import pandas as pd from numpy.typing import NDArray -# Placeholders (Any) until ipc.pyi and scalar.pyi are annotated; mypy -# rejects them as types when imported through pyarrow.lib. +# Placeholder (Any) until ipc.pyi is annotated; mypy rejects it as a type +# when imported through pyarrow.lib. from pyarrow.__lib.ipc import RecordBatchReader -from pyarrow.__lib.scalar import Int64Scalar, Scalar from pyarrow._compute import ( CastOptions, CountOptions, @@ -65,8 +64,10 @@ from pyarrow.lib import ( Device, DeviceAllocationType, Field, + Int64Scalar, MemoryManager, MemoryPool, + Scalar, Schema, StructArray, Tensor, 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/_azurefs.pyi b/python/pyarrow-stubs/_azurefs.pyi new file mode 100644 index 00000000000..ab0e3610f73 --- /dev/null +++ b/python/pyarrow-stubs/_azurefs.pyi @@ -0,0 +1,35 @@ +# 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 Literal + +from ._fs import FileSystem + +class AzureFileSystem(FileSystem): + def __init__( + self, + account_name: str | None = None, + account_key: str | None = None, + blob_storage_authority: str | None = None, + dfs_storage_authority: str | None = None, + blob_storage_scheme: Literal["http", "https"] = "https", + dfs_storage_scheme: Literal["http", "https"] = "https", + sas_token: str | None = None, + tenant_id: str | None = None, + client_id: str | None = None, + client_secret: str | None = None, + ) -> None: ... diff --git a/python/pyarrow-stubs/_compute.pyi b/python/pyarrow-stubs/_compute.pyi index 3108cb06374..ad7e7b8a1b5 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 +# Placeholders (Any) until ipc.pyi and scalar.pyi are annotated; mypy +# rejects them as types when imported through pyarrow.lib. +from pyarrow.__lib.ipc import RecordBatchReader +from pyarrow.__lib.scalar import Scalar +from pyarrow._stubs_typing import ( + NullEncoding, + NullPlacement, + NullSelectionBehavior, + Order, + TimeUnit, +) +from pyarrow.lib import ( + Array, + Buffer, + ChunkedArray, + DataType, + KeyValueMetadata, + MemoryPool, + Schema, + _Weakrefable, +) -Expression: TypeAlias = Any +_RoundMode: TypeAlias = Literal[ + "down", + "up", + "towards_zero", + "towards_infinity", + "half_down", + "half_up", + "half_towards_zero", + "half_towards_infinity", + "half_to_even", + "half_to_odd", +] +_DateTimeUnit: TypeAlias = Literal[ + "year", + "quarter", + "month", + "week", + "day", + "hour", + "minute", + "second", + "millisecond", + "microsecond", + "nanosecond", +] +# Sort keys are (name, order) or (name, order, null_placement) tuples; the +# null_placement arguments of the options are deprecated. +_SortKey: TypeAlias = ( + tuple[str | Expression | 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/_cuda.pyi b/python/pyarrow-stubs/_cuda.pyi new file mode 100644 index 00000000000..84a66ff83ec --- /dev/null +++ b/python/pyarrow-stubs/_cuda.pyi @@ -0,0 +1,118 @@ +# 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 Any + +import cuda +from numba.cuda.cudadrv import driver as _numba_driver +from numpy.typing import ArrayLike + +from . import lib + +class Context(lib._Weakrefable): + def __init__(self, device_number: int = 0, handle: int | None = None) -> None: ... + @staticmethod + def from_numba(context: _numba_driver.Context | None = None) -> Context: ... + def to_numba(self) -> _numba_driver.Context: ... + @staticmethod + def get_num_devices() -> int: ... + @property + def device_number(self) -> int: ... + @property + def handle(self) -> int: ... + def synchronize(self) -> None: ... + @property + def bytes_allocated(self) -> int: ... + def get_device_address(self, address: int) -> int: ... + def new_buffer(self, nbytes: int) -> CudaBuffer: ... + @property + def memory_manager(self) -> lib.MemoryManager: ... + @property + def device(self) -> lib.Device: ... + def foreign_buffer( + self, address: int, size: int, base: Any | None = None + ) -> CudaBuffer: ... + def open_ipc_buffer(self, ipc_handle: IpcMemHandle) -> CudaBuffer: ... + def buffer_from_data( + self, + data: CudaBuffer | HostBuffer | lib.Buffer | ArrayLike, + offset: int = 0, + size: int = -1, + ) -> CudaBuffer: ... + def buffer_from_object(self, obj: Any) -> CudaBuffer: ... + +class IpcMemHandle(lib._Weakrefable): + @staticmethod + def from_buffer(opaque_handle: lib.Buffer) -> IpcMemHandle: ... + def serialize(self, pool: lib.MemoryPool | None = None) -> lib.Buffer: ... + +class CudaBuffer(lib.Buffer): + @staticmethod + def from_buffer(buf: lib.Buffer) -> CudaBuffer: ... + @staticmethod + def from_numba(mem: _numba_driver.MemoryPointer) -> CudaBuffer: ... + def to_numba(self) -> _numba_driver.MemoryPointer: ... + def copy_to_host( + self, + position: int = 0, + nbytes: int = -1, + buf: lib.Buffer | None = None, + memory_pool: lib.MemoryPool | None = None, + resizable: bool = False, + ) -> lib.Buffer: ... + def copy_from_host( + self, data: lib.Buffer | ArrayLike, position: int = 0, nbytes: int = -1 + ) -> int: ... + def copy_from_device( + self, buf: CudaBuffer, position: int = 0, nbytes: int = -1 + ) -> int: ... + def export_for_ipc(self) -> IpcMemHandle: ... + @property + def context(self) -> Context: ... + def slice(self, offset: int = 0, length: int | None = None) -> CudaBuffer: ... + def to_pybytes(self) -> bytes: ... + +class HostBuffer(lib.Buffer): + @property + def size(self) -> int: ... + +class BufferReader(lib.NativeFile): + def __init__(self, obj: CudaBuffer) -> None: ... + def read_buffer(self, nbytes: int | None = None) -> CudaBuffer: ... + +class BufferWriter(lib.NativeFile): + def __init__(self, obj: CudaBuffer) -> None: ... + def writeat(self, position: int, data: ArrayLike) -> None: ... + @property + def buffer_size(self) -> int: ... + @buffer_size.setter + def buffer_size(self, buffer_size: int) -> None: ... + @property + def num_bytes_buffered(self) -> int: ... + +def new_host_buffer(size: int, device: int = 0) -> HostBuffer: ... +def serialize_record_batch(batch: lib.RecordBatch, ctx: Context) -> CudaBuffer: ... +def read_message( + source: CudaBuffer | cuda.BufferReader, pool: lib.MemoryManager | None = None +) -> lib.Message: ... +def read_record_batch( + buffer: lib.Buffer, + object: lib.Schema, + *, + dictionary_memo: lib.DictionaryMemo | None = None, + pool: lib.MemoryPool | None = None, +) -> lib.RecordBatch: ... diff --git a/python/pyarrow-stubs/_dataset.pyi b/python/pyarrow-stubs/_dataset.pyi new file mode 100644 index 00000000000..ca4fa879afd --- /dev/null +++ b/python/pyarrow-stubs/_dataset.pyi @@ -0,0 +1,595 @@ +# 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, Collection, Iterable, Iterator +from typing import ( + IO, + Any, + Generic, + Literal, + NamedTuple, + Self, + TypeVar, +) + +from _typeshed import StrPath + +from . import _json, _parquet, csv, lib +from ._acero import ExecNodeOptions +from ._fs import FileSelector, FileSystem, _SupportedFileSystem +from ._stubs_typing import Indices, JoinType, Order +from .compute import Expression +from .ipc import IpcWriteOptions, RecordBatchReader + +class Dataset(lib._Weakrefable): + @property + def partition_expression(self) -> Expression: ... + def replace_schema(self, schema: lib.Schema) -> Self: ... + def get_fragments(self, filter: Expression | None = None) -> Iterator[Fragment]: ... + def scanner( + self, + columns: list[str] | dict[str, Expression] | None = None, + filter: Expression | None = None, + batch_size: int = ..., + batch_readahead: int = 16, + fragment_readahead: int = 4, + fragment_scan_options: FragmentScanOptions | None = None, + use_threads: bool = True, + cache_metadata: bool = True, + memory_pool: lib.MemoryPool | None = None, + ) -> Scanner: ... + def to_batches( + self, + columns: list[str] | None = None, + filter: Expression | None = None, + batch_size: int = ..., + batch_readahead: int = 16, + fragment_readahead: int = 4, + fragment_scan_options: FragmentScanOptions | None = None, + use_threads: bool = True, + cache_metadata: bool = True, + memory_pool: lib.MemoryPool | None = None, + ) -> Iterator[lib.RecordBatch]: ... + def to_table( + self, + columns: list[str] | dict[str, Expression] | None = None, + filter: Expression | None = None, + batch_size: int = ..., + batch_readahead: int = 16, + fragment_readahead: int = 4, + fragment_scan_options: FragmentScanOptions | None = None, + use_threads: bool = True, + cache_metadata: bool = True, + memory_pool: lib.MemoryPool | None = None, + ) -> lib.Table: ... + def take( + self, + indices: Indices, + columns: list[str] | None = None, + filter: Expression | None = None, + batch_size: int = ..., + batch_readahead: int = 16, + fragment_readahead: int = 4, + fragment_scan_options: FragmentScanOptions | None = None, + use_threads: bool = True, + cache_metadata: bool = True, + memory_pool: lib.MemoryPool | None = None, + ) -> lib.Table: ... + def head( + self, + num_rows: int, + columns: list[str] | None = None, + filter: Expression | None = None, + batch_size: int = ..., + batch_readahead: int = 16, + fragment_readahead: int = 4, + fragment_scan_options: FragmentScanOptions | None = None, + use_threads: bool = True, + cache_metadata: bool = True, + memory_pool: lib.MemoryPool | None = None, + ) -> lib.Table: ... + def count_rows( + self, + filter: Expression | None = None, + batch_size: int = ..., + batch_readahead: int = 16, + fragment_readahead: int = 4, + fragment_scan_options: FragmentScanOptions | None = None, + use_threads: bool = True, + cache_metadata: bool = True, + memory_pool: lib.MemoryPool | None = None, + ) -> int: ... + @property + def schema(self) -> lib.Schema: ... + def filter(self, expression: Expression | None) -> Self: ... + def sort_by( + self, sorting: str | list[tuple[str, Order]], **kwargs: Any + ) -> InMemoryDataset: ... + def join( + self, + right_dataset: Dataset, + keys: str | list[str], + right_keys: str | list[str] | None = None, + join_type: JoinType = "left outer", + left_suffix: str | None = None, + right_suffix: str | None = None, + coalesce_keys: bool = True, + use_threads: bool = True, + ) -> InMemoryDataset: ... + def join_asof( + self, + right_dataset: Dataset, + on: str, + by: str | list[str], + tolerance: int, + right_on: str | list[str] | None = None, + right_by: str | list[str] | None = None, + ) -> InMemoryDataset: ... + @property + def format(self) -> FileFormat: ... + +class InMemoryDataset(Dataset): + def __init__( + self, + source: lib.Table + | lib.RecordBatch + | lib.RecordBatchReader + | Iterable[lib.RecordBatch] + | list[Any], + schema: lib.Schema | None = None, + ) -> None: ... + +class FilteredDataset(Dataset): + def __init__(self, child: Dataset, filter: Expression) -> None: ... + @property + def child(self) -> Dataset: ... + @property + def filter_expression(self) -> Expression: ... + +class UnionDataset(Dataset): + def __init__( + self, + schema: lib.Schema | None = None, + children: list[Dataset] | None = None, + ) -> None: ... + @property + def children(self) -> list[Dataset]: ... + +class FileSystemDataset(Dataset): + def __init__( + self, + fragments: list[Fragment], + schema: lib.Schema, + format: FileFormat, + filesystem: _SupportedFileSystem | None = None, + root_partition: Expression | None = None, + ) -> None: ... + @classmethod + def from_paths( + cls, + paths: list[str], + schema: lib.Schema | None = None, + format: FileFormat | None = None, + filesystem: _SupportedFileSystem | None = None, + partitions: list[Expression] | None = None, + root_partition: Expression | None = None, + ) -> FileSystemDataset: ... + @property + def filesystem(self) -> FileSystem: ... + @property + def partitioning(self) -> Partitioning | None: ... + @property + def files(self) -> list[str]: ... + +class FileWriteOptions(lib._Weakrefable): + @property + def format(self) -> FileFormat: ... + +class FileFormat(lib._Weakrefable): + def inspect( + self, file: StrPath | IO[Any], filesystem: _SupportedFileSystem | None = None + ) -> lib.Schema: ... + def make_fragment( + self, + file: StrPath | IO[Any] | lib.Buffer | lib.BufferReader, + filesystem: _SupportedFileSystem | None = None, + partition_expression: Expression | None = None, + *, + file_size: int | None = None, + ) -> Fragment: ... + def make_write_options(self) -> FileWriteOptions: ... + @property + def default_extname(self) -> str: ... + @property + def default_fragment_scan_options(self) -> FragmentScanOptions: ... + @default_fragment_scan_options.setter + def default_fragment_scan_options(self, options: FragmentScanOptions) -> None: ... + +class Fragment(lib._Weakrefable): + @property + def physical_schema(self) -> lib.Schema: ... + @property + def partition_expression(self) -> Expression: ... + def scanner( + self, + schema: lib.Schema | None = None, + columns: list[str] | None = None, + filter: Expression | None = None, + batch_size: int = ..., + batch_readahead: int = 16, + fragment_readahead: int = 4, + fragment_scan_options: FragmentScanOptions | None = None, + use_threads: bool = True, + cache_metadata: bool = True, + memory_pool: lib.MemoryPool | None = None, + ) -> Scanner: ... + def to_batches( + self, + schema: lib.Schema | None = None, + columns: list[str] | None = None, + filter: Expression | None = None, + batch_size: int = ..., + batch_readahead: int = 16, + fragment_readahead: int = 4, + fragment_scan_options: FragmentScanOptions | None = None, + use_threads: bool = True, + cache_metadata: bool = True, + memory_pool: lib.MemoryPool | None = None, + ) -> Iterator[lib.RecordBatch]: ... + def to_table( + self, + schema: lib.Schema | None = None, + columns: list[str] | None = None, + filter: Expression | None = None, + batch_size: int = ..., + batch_readahead: int = 16, + fragment_readahead: int = 4, + fragment_scan_options: FragmentScanOptions | None = None, + use_threads: bool = True, + cache_metadata: bool = True, + memory_pool: lib.MemoryPool | None = None, + ) -> lib.Table: ... + def take( + self, + indices: Indices, + columns: list[str] | None = None, + filter: Expression | None = None, + batch_size: int = ..., + batch_readahead: int = 16, + fragment_readahead: int = 4, + fragment_scan_options: FragmentScanOptions | None = None, + use_threads: bool = True, + cache_metadata: bool = True, + memory_pool: lib.MemoryPool | None = None, + ) -> lib.Table: ... + def head( + self, + num_rows: int, + columns: list[str] | None = None, + filter: Expression | None = None, + batch_size: int = ..., + batch_readahead: int = 16, + fragment_readahead: int = 4, + fragment_scan_options: FragmentScanOptions | None = None, + use_threads: bool = True, + cache_metadata: bool = True, + memory_pool: lib.MemoryPool | None = None, + ) -> lib.Table: ... + def count_rows( + self, + filter: Expression | None = None, + batch_size: int = ..., + batch_readahead: int = 16, + fragment_readahead: int = 4, + fragment_scan_options: FragmentScanOptions | None = None, + use_threads: bool = True, + cache_metadata: bool = True, + memory_pool: lib.MemoryPool | None = None, + ) -> int: ... + +class FilteredFragment(Fragment): + @property + def fragment(self) -> Fragment: ... + @property + def filter_expression(self) -> Expression: ... + +class FileFragment(Fragment): + def open(self) -> lib.NativeFile: ... + @property + def path(self) -> str: ... + @property + def filesystem(self) -> FileSystem: ... + @property + def buffer(self) -> lib.Buffer: ... + @property + def format(self) -> FileFormat: ... + +class FragmentScanOptions(lib._Weakrefable): + @property + def type_name(self) -> str: ... + +class IpcFileWriteOptions(FileWriteOptions): + @property + def write_options(self) -> IpcWriteOptions: ... + @write_options.setter + def write_options(self, write_options: IpcWriteOptions) -> None: ... + +class IpcFileFormat(FileFormat): + def equals(self, other: IpcFileFormat) -> bool: ... + def make_write_options(self, **kwargs: Any) -> IpcFileWriteOptions: ... + @property + def default_extname(self) -> str: ... + +class FeatherFileFormat(IpcFileFormat): ... + +class CsvFileFormat(FileFormat): + def __init__( + self, + parse_options: csv.ParseOptions | None = None, + default_fragment_scan_options: CsvFragmentScanOptions | None = None, + convert_options: csv.ConvertOptions | None = None, + read_options: csv.ReadOptions | None = None, + ) -> None: ... + def make_write_options(self, **kwargs: Any) -> CsvFileWriteOptions: ... + @property + def parse_options(self) -> csv.ParseOptions: ... + @parse_options.setter + def parse_options(self, parse_options: csv.ParseOptions) -> None: ... + def equals(self, other: CsvFileFormat) -> bool: ... + +class CsvFragmentScanOptions(FragmentScanOptions): + convert_options: csv.ConvertOptions + read_options: csv.ReadOptions + + def __init__( + self, + convert_options: csv.ConvertOptions | None = None, + read_options: csv.ReadOptions | None = None, + ) -> None: ... + def equals(self, other: CsvFragmentScanOptions) -> bool: ... + +class CsvFileWriteOptions(FileWriteOptions): + write_options: csv.WriteOptions + +class JsonFileFormat(FileFormat): + def __init__( + self, + default_fragment_scan_options: JsonFragmentScanOptions | None = None, + parse_options: _json.ParseOptions | None = None, + read_options: _json.ReadOptions | None = None, + ) -> None: ... + def equals(self, other: JsonFileFormat) -> bool: ... + +class JsonFragmentScanOptions(FragmentScanOptions): + parse_options: _json.ParseOptions + read_options: _json.ReadOptions + + def __init__( + self, + parse_options: _json.ParseOptions | None = None, + read_options: _json.ReadOptions | None = None, + ) -> None: ... + def equals(self, other: JsonFragmentScanOptions) -> bool: ... + +class Partitioning(lib._Weakrefable): + def parse(self, path: str) -> Expression: ... + def format(self, expr: Expression) -> tuple[str, str]: ... + @property + def schema(self) -> lib.Schema: ... + @property + def dictionaries(self) -> list[Any]: ... + +class PartitioningFactory(lib._Weakrefable): + @property + def type_name(self) -> str: ... + +class KeyValuePartitioning(Partitioning): + @property + def dictionaries(self) -> list[Any]: ... + +class DirectoryPartitioning(KeyValuePartitioning): + @staticmethod + def discover( + field_names: list[str] | None = None, + infer_dictionary: bool = False, + max_partition_dictionary_size: int = 0, + schema: lib.Schema | None = None, + segment_encoding: Literal["uri", "none"] = "uri", + ) -> PartitioningFactory: ... + def __init__( + self, + schema: lib.Schema, + dictionaries: dict[str, lib.Array] | None = None, + segment_encoding: Literal["uri", "none"] = "uri", + ) -> None: ... + +class HivePartitioning(KeyValuePartitioning): + def __init__( + self, + schema: lib.Schema, + dictionaries: dict[str, lib.Array] | None = None, + null_fallback: str = "__HIVE_DEFAULT_PARTITION__", + segment_encoding: Literal["uri", "none"] = "uri", + ) -> None: ... + @staticmethod + def discover( + infer_dictionary: bool = False, + max_partition_dictionary_size: int = 0, + null_fallback: str = "__HIVE_DEFAULT_PARTITION__", + schema: lib.Schema | None = None, + segment_encoding: Literal["uri", "none"] = "uri", + ) -> PartitioningFactory: ... + +class FilenamePartitioning(KeyValuePartitioning): + def __init__( + self, + schema: lib.Schema, + dictionaries: dict[str, lib.Array] | None = None, + segment_encoding: Literal["uri", "none"] = "uri", + ) -> None: ... + @staticmethod + def discover( + field_names: list[str] | None = None, + infer_dictionary: bool = False, + schema: lib.Schema | None = None, + segment_encoding: Literal["uri", "none"] = "uri", + ) -> PartitioningFactory: ... + +class DatasetFactory(lib._Weakrefable): + root_partition: Expression + def finish(self, schema: lib.Schema | None = None) -> Dataset: ... + def inspect( + self, + *, + promote_options: str = "default", + fragments: list[Fragment] | int | str | None = None, + ) -> lib.Schema: ... + def inspect_schemas(self) -> list[lib.Schema]: ... + +class FileSystemFactoryOptions(lib._Weakrefable): + partitioning: Partitioning + partitioning_factory: PartitioningFactory + partition_base_dir: str + exclude_invalid_files: bool + selector_ignore_prefixes: list[str] + + def __init__( + self, + partition_base_dir: str | None = None, + partitioning: Partitioning | PartitioningFactory | None = None, + exclude_invalid_files: bool | None = True, + selector_ignore_prefixes: list[str] | None = None, + ) -> None: ... + +class FileSystemDatasetFactory(DatasetFactory): + def __init__( + self, + filesystem: _SupportedFileSystem, + paths_or_selector: Collection[str] | FileSelector, + format: FileFormat, + options: FileSystemFactoryOptions | None = None, + ) -> None: ... + +class UnionDatasetFactory(DatasetFactory): + def __init__(self, factories: list[DatasetFactory]) -> None: ... + +_RecordBatchT = TypeVar("_RecordBatchT", bound=lib.RecordBatch) + +class RecordBatchIterator(lib._Weakrefable, Generic[_RecordBatchT]): + def __iter__(self) -> Self: ... + def __next__(self) -> _RecordBatchT: ... + +class TaggedRecordBatch(NamedTuple): + record_batch: lib.RecordBatch + fragment: Fragment + +class TaggedRecordBatchIterator(lib._Weakrefable): + def __iter__(self) -> Self: ... + def __next__(self) -> TaggedRecordBatch: ... + +class Scanner(lib._Weakrefable): + @staticmethod + def from_dataset( + dataset: Dataset, + *, + columns: list[str] | dict[str, Expression] | None = None, + filter: Expression | None = None, + batch_size: int = ..., + batch_readahead: int = 16, + fragment_readahead: int = 4, + fragment_scan_options: FragmentScanOptions | None = None, + use_threads: bool = True, + cache_metadata: bool = True, + memory_pool: lib.MemoryPool | None = None, + ) -> Scanner: ... + @staticmethod + def from_fragment( + fragment: Fragment, + *, + schema: lib.Schema | None = None, + columns: list[str] | dict[str, Expression] | None = None, + filter: Expression | None = None, + batch_size: int = ..., + batch_readahead: int = 16, + fragment_readahead: int = 4, + fragment_scan_options: FragmentScanOptions | None = None, + use_threads: bool = True, + cache_metadata: bool = True, + memory_pool: lib.MemoryPool | None = None, + ) -> Scanner: ... + @staticmethod + def from_batches( + source: Iterator[lib.RecordBatch] | RecordBatchReader | Any, + *, + schema: lib.Schema | None = None, + columns: list[str] | dict[str, Expression] | None = None, + filter: Expression | None = None, + batch_size: int = ..., + batch_readahead: int = 16, + fragment_readahead: int = 4, + fragment_scan_options: FragmentScanOptions | None = None, + use_threads: bool = True, + cache_metadata: bool = True, + memory_pool: lib.MemoryPool | None = None, + ) -> Scanner: ... + @property + def dataset_schema(self) -> lib.Schema: ... + @property + def projected_schema(self) -> lib.Schema: ... + def to_batches(self) -> Iterator[lib.RecordBatch]: ... + def scan_batches(self) -> TaggedRecordBatchIterator: ... + def to_table(self) -> lib.Table: ... + def take(self, indices: Indices) -> lib.Table: ... + def head(self, num_rows: int) -> lib.Table: ... + def count_rows(self) -> int: ... + def to_reader(self) -> RecordBatchReader: ... + +def get_partition_keys(partition_expression: Expression) -> dict[str, Any]: ... + +class WrittenFile(lib._Weakrefable): + path: str + metadata: _parquet.FileMetaData | None + size: int + def __init__( + self, path: str, metadata: _parquet.FileMetaData | None, size: int + ) -> None: ... + +def _filesystemdataset_write( + data: Scanner, + base_dir: StrPath, + basename_template: str, + filesystem: _SupportedFileSystem, + partitioning: Partitioning, + preserve_order: bool, + file_options: FileWriteOptions, + max_partitions: int, + file_visitor: Callable[[str], None] | None, + existing_data_behavior: Literal["error", "overwrite_or_ignore", "delete_matching"], + max_open_files: int, + max_rows_per_file: int, + min_rows_per_group: int, + max_rows_per_group: int, + create_dir: bool, +) -> None: ... + +class _ScanNodeOptions(ExecNodeOptions): + def _set_options(self, dataset: Dataset, scan_options: dict[str, Any]) -> None: ... + +class ScanNodeOptions(_ScanNodeOptions): + def __init__( + self, dataset: Dataset, *, require_sequenced_output: bool = False, **kwargs: Any + ) -> None: ... diff --git a/python/pyarrow-stubs/_dataset_orc.pyi b/python/pyarrow-stubs/_dataset_orc.pyi new file mode 100644 index 00000000000..ae20cb9b1e9 --- /dev/null +++ b/python/pyarrow-stubs/_dataset_orc.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 ._dataset import FileFormat + +class OrcFileFormat(FileFormat): + def equals(self, other: OrcFileFormat) -> bool: ... + @property + def default_extname(self) -> str: ... diff --git a/python/pyarrow-stubs/_dataset_parquet.pyi b/python/pyarrow-stubs/_dataset_parquet.pyi new file mode 100644 index 00000000000..d676e7d9a61 --- /dev/null +++ b/python/pyarrow-stubs/_dataset_parquet.pyi @@ -0,0 +1,209 @@ +# 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, TypedDict + +from _typeshed import StrPath + +from ._compute import Expression +from ._dataset import ( + DatasetFactory, + FileFormat, + FileFragment, + FileWriteOptions, + Fragment, + FragmentScanOptions, + Partitioning, + PartitioningFactory, +) +from ._dataset_parquet_encryption import ParquetDecryptionConfig +from ._fs import FileSystem, _SupportedFileSystem +from ._parquet import FileDecryptionProperties, FileMetaData +from .lib import ( + Buffer, + BufferReader, + CacheOptions, + DataType, + LargeListType, + ListType, + NativeFile, + Schema, + _Weakrefable, +) + +parquet_encryption_enabled: bool + +class ParquetFileFormat(FileFormat): + def __init__( + self, + read_options: ParquetReadOptions | None = None, + default_fragment_scan_options: ParquetFragmentScanOptions | None = None, + *, + pre_buffer: bool = True, + coerce_int96_timestamp_unit: str | None = None, + thrift_string_size_limit: int | None = None, + thrift_container_size_limit: int | None = None, + page_checksum_verification: bool = False, + arrow_extensions_enabled: bool = True, + binary_type: DataType | None = None, + list_type: type[ListType | LargeListType] | None = None, + use_buffered_stream: bool = False, + buffer_size: int = 8192, + dictionary_columns: list[str] | set[str] | None = None, + decryption_properties: FileDecryptionProperties | None = None, + ) -> None: ... + @property + def read_options(self) -> ParquetReadOptions: ... + def make_write_options(self, **kwargs: Any) -> ParquetFileWriteOptions: ... + def equals(self, other: ParquetFileFormat) -> bool: ... + @property + def default_extname(self) -> str: ... + def make_fragment( + self, + file: StrPath | IO[Any] | Buffer | BufferReader, + filesystem: _SupportedFileSystem | None = None, + partition_expression: Expression | None = None, + row_groups: Iterable[int] | None = None, + *, + file_size: int | None = None, + ) -> Fragment: ... + +class _NameStats(TypedDict): + min: Any + max: Any + +class RowGroupInfo: + id: int + metadata: FileMetaData + schema: Schema + + def __init__(self, id: int, metadata: FileMetaData, schema: Schema) -> None: ... + @property + def num_rows(self) -> int: ... + @property + def total_byte_size(self) -> int: ... + @property + def statistics(self) -> dict[str, _NameStats]: ... + +class ParquetFileFragment(FileFragment): + def ensure_complete_metadata(self) -> None: ... + @property + def path(self) -> str: ... + @property + def filesystem(self) -> FileSystem: ... + def open(self) -> NativeFile: ... + @property + def row_groups(self) -> list[int]: ... + @property + def metadata(self) -> FileMetaData: ... + @property + def num_row_groups(self) -> int: ... + def split_by_row_group( + self, filter: Expression | None = None, schema: Schema | None = None + ) -> list[Fragment]: ... + def subset( + self, + filter: Expression | None = None, + schema: Schema | None = None, + row_group_ids: list[int] | None = None, + ) -> ParquetFileFormat: ... + +class ParquetReadOptions(_Weakrefable): + def __init__( + self, + dictionary_columns: list[str] | set[str] | None = None, + coerce_int96_timestamp_unit: str | None = None, + binary_type: DataType | None = None, + list_type: type[ListType | LargeListType] | None = None, + ) -> None: ... + @property + def dictionary_columns(self) -> set[str]: ... + @dictionary_columns.setter + def dictionary_columns(self, columns: list[str] | set[str]) -> None: ... + @property + def coerce_int96_timestamp_unit(self) -> str: ... + @coerce_int96_timestamp_unit.setter + def coerce_int96_timestamp_unit(self, unit: str) -> None: ... + @property + def binary_type(self) -> DataType: ... + @binary_type.setter + def binary_type(self, type: DataType | None) -> None: ... + @property + def list_type(self) -> type[ListType | LargeListType]: ... + @list_type.setter + def list_type(self, type: type[ListType | LargeListType] | None) -> None: ... + def equals(self, other: ParquetReadOptions) -> bool: ... + +class ParquetFileWriteOptions(FileWriteOptions): + def update(self, **kwargs: Any) -> None: ... + def _set_properties(self) -> None: ... + def _set_arrow_properties(self) -> None: ... + def _set_encryption_config(self) -> None: ... + # accept passthrough options used in tests + def __init__(self, **kwargs: Any) -> None: ... + +class ParquetFragmentScanOptions(FragmentScanOptions): + use_buffered_stream: bool + buffer_size: int + pre_buffer: bool + cache_options: CacheOptions | None + thrift_string_size_limit: int | None + thrift_container_size_limit: int | None + decryption_config: ParquetDecryptionConfig | None + decryption_properties: FileDecryptionProperties | None + parquet_decryption_config: ParquetDecryptionConfig | None + page_checksum_verification: bool + arrow_extensions_enabled: bool + + def __init__( + self, + *, + use_buffered_stream: bool = False, + buffer_size: int = 8192, + pre_buffer: bool = True, + cache_options: CacheOptions | None = None, + thrift_string_size_limit: int | None = None, + thrift_container_size_limit: int | None = None, + decryption_config: ParquetDecryptionConfig | None = None, + decryption_properties: FileDecryptionProperties | None = None, + page_checksum_verification: bool = False, + arrow_extensions_enabled: bool = True, + ) -> None: ... + def equals(self, other: ParquetFragmentScanOptions) -> bool: ... + +class ParquetFactoryOptions(_Weakrefable): + partition_base_dir: str | None + partitioning: Partitioning | PartitioningFactory | None + partitioning_factory: PartitioningFactory | None + validate_column_chunk_paths: bool + + def __init__( + self, + partition_base_dir: str | None = None, + partitioning: Partitioning | PartitioningFactory | None = None, + validate_column_chunk_paths: bool = False, + ) -> None: ... + +class ParquetDatasetFactory(DatasetFactory): + def __init__( + self, + metadata_path: str, + filesystem: _SupportedFileSystem, + format: FileFormat, + options: ParquetFactoryOptions | None = None, + ) -> None: ... diff --git a/python/pyarrow-stubs/_dataset_parquet_encryption.pyi b/python/pyarrow-stubs/_dataset_parquet_encryption.pyi new file mode 100644 index 00000000000..265475aacf8 --- /dev/null +++ b/python/pyarrow-stubs/_dataset_parquet_encryption.pyi @@ -0,0 +1,55 @@ +# 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 ._dataset_parquet import ParquetFileWriteOptions, ParquetFragmentScanOptions +from ._parquet import FileDecryptionProperties +from ._parquet_encryption import ( + CryptoFactory, + EncryptionConfiguration, + DecryptionConfiguration, + KmsConnectionConfig, +) +from .lib import _Weakrefable + +class ParquetEncryptionConfig(_Weakrefable): + def __init__( + self, + crypto_factory: CryptoFactory, + kms_connection_config: KmsConnectionConfig, + encryption_config: EncryptionConfiguration, + ) -> None: ... + +class ParquetDecryptionConfig(_Weakrefable): + def __init__( + self, + crypto_factory: CryptoFactory, + kms_connection_config: KmsConnectionConfig, + decryption_config: DecryptionConfiguration, + ) -> None: ... + +def set_encryption_config( + opts: ParquetFileWriteOptions, + config: ParquetEncryptionConfig, +) -> None: ... +def set_decryption_properties( + opts: ParquetFragmentScanOptions, + config: FileDecryptionProperties, +) -> None: ... +def set_decryption_config( + opts: ParquetFragmentScanOptions, + config: ParquetDecryptionConfig, +) -> 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/_flight.pyi b/python/pyarrow-stubs/_flight.pyi new file mode 100644 index 00000000000..ce8cc0c008d --- /dev/null +++ b/python/pyarrow-stubs/_flight.pyi @@ -0,0 +1,531 @@ +# 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 asyncio +import enum +from collections.abc import Iterable, Iterator, Sequence +from datetime import datetime +from typing import Any, Generic, NamedTuple, Self, TypeVar + +from typing_extensions import deprecated + +from .ipc import _ReadPandasMixin, ReadStats +from .lib import ( + ArrowCancelled, + ArrowException, + ArrowInvalid, + Buffer, + IpcReadOptions, + IpcWriteOptions, + RecordBatch, + RecordBatchReader, + Scalar, + Schema, + Table, + _CRecordBatchWriter, + _Weakrefable, +) + +_T = TypeVar("_T") + +class FlightCallOptions(_Weakrefable): + def __init__( + self, + timeout: float | None = None, + write_options: IpcWriteOptions | None = None, + headers: Sequence[tuple[str | bytes, str | bytes]] | None = None, + read_options: IpcReadOptions | None = None, + ) -> None: ... + @property + def timeout(self) -> float: ... + @property + def headers(self) -> list[tuple[bytes, bytes]]: ... + @property + def read_options(self) -> IpcReadOptions: ... + @property + def write_options(self) -> IpcWriteOptions: ... + +class CertKeyPair(NamedTuple): + cert: str | bytes | None + key: str | bytes | None + +class FlightError(Exception): + extra_info: bytes + +class FlightInternalError(FlightError, ArrowException): ... +class FlightTimedOutError(FlightError, ArrowException): ... + +class FlightCancelledError(FlightError, ArrowCancelled): + def __init__(self, message: str, *, extra_info: bytes | None = None) -> None: ... + +class FlightServerError(FlightError, ArrowException): ... +class FlightUnauthenticatedError(FlightError, ArrowException): ... +class FlightUnauthorizedError(FlightError, ArrowException): ... +class FlightUnavailableError(FlightError, ArrowException): ... + +class FlightWriteSizeExceededError(ArrowInvalid): + limit: int + actual: int + def __init__(self, message: str, limit: int, actual: int) -> None: ... + +class Action(_Weakrefable): + def __init__( + self, action_type: bytes | str, buf: Buffer | bytes | None + ) -> None: ... + @property + def type(self) -> str: ... + @property + def body(self) -> Buffer: ... + def serialize(self) -> bytes: ... + @classmethod + def deserialize(cls, serialized: bytes) -> Self: ... + +class ActionType(NamedTuple): + type: str + description: str + + def make_action(self, buf: Buffer | bytes) -> Action: ... + +class Result(_Weakrefable): + def __init__(self, buf: Buffer | bytes) -> None: ... + @property + def body(self) -> Buffer: ... + def serialize(self) -> bytes: ... + @classmethod + def deserialize(cls, serialized: bytes) -> Self: ... + +class BasicAuth(_Weakrefable): + def __init__( + self, username: str | bytes | None = None, password: str | bytes | None = None + ) -> None: ... + @property + def username(self) -> bytes: ... + @property + def password(self) -> bytes: ... + def serialize(self) -> str: ... + @staticmethod + def deserialize(serialized: str | bytes) -> BasicAuth: ... + +class DescriptorType(enum.Enum): + UNKNOWN = 0 + PATH = 1 + CMD = 2 + +class FlightMethod(enum.Enum): + INVALID = 0 + HANDSHAKE = 1 + LIST_FLIGHTS = 2 + GET_FLIGHT_INFO = 3 + GET_SCHEMA = 4 + DO_GET = 5 + DO_PUT = 6 + DO_ACTION = 7 + LIST_ACTIONS = 8 + DO_EXCHANGE = 9 + +class FlightDescriptor(_Weakrefable): + @staticmethod + def for_path(*path: str | bytes) -> FlightDescriptor: ... + @staticmethod + def for_command(command: str | bytes) -> FlightDescriptor: ... + @property + def descriptor_type(self) -> DescriptorType: ... + @property + def path(self) -> list[bytes] | None: ... + @property + def command(self) -> bytes | None: ... + def serialize(self) -> bytes: ... + @classmethod + def deserialize(cls, serialized: bytes) -> Self: ... + +class Ticket(_Weakrefable): + def __init__(self, ticket: str | bytes) -> None: ... + @property + def ticket(self) -> bytes: ... + def serialize(self) -> bytes: ... + @classmethod + def deserialize(cls, serialized: bytes) -> Self: ... + +class Location(_Weakrefable): + def __init__(self, uri: str | bytes) -> None: ... + @property + def uri(self) -> bytes: ... + def equals(self, other: Location) -> bool: ... + @staticmethod + def for_grpc_tcp(host: str | bytes, port: int) -> Location: ... + @staticmethod + def for_grpc_tls(host: str | bytes, port: int) -> Location: ... + @staticmethod + def for_grpc_unix(path: str | bytes) -> Location: ... + +class FlightEndpoint(_Weakrefable): + def __init__( + self, + ticket: Ticket | str | bytes | object, + locations: Sequence[str | bytes | Location | object], + expiration_time: Scalar | str | datetime | None = ..., + app_metadata: bytes | str | object = ..., + ) -> None: ... + @property + def ticket(self) -> Ticket: ... + @property + def locations(self) -> list[Location]: ... + def serialize(self) -> bytes: ... + @property + def expiration_time(self) -> Scalar | None: ... + @property + def app_metadata(self) -> bytes | str: ... + @classmethod + def deserialize(cls, serialized: bytes) -> Self: ... + +class SchemaResult(_Weakrefable): + def __init__(self, schema: Schema) -> None: ... + @property + def schema(self) -> Schema: ... + def serialize(self) -> bytes: ... + @classmethod + def deserialize(cls, serialized: bytes) -> Self: ... + +class FlightInfo(_Weakrefable): + def __init__( + self, + schema: Schema | None, + descriptor: FlightDescriptor, + endpoints: list[FlightEndpoint], + total_records: int | None = ..., + total_bytes: int | None = ..., + ordered: bool = ..., + app_metadata: bytes | str = ..., + ) -> None: ... + @property + def schema(self) -> Schema | None: ... + @property + def descriptor(self) -> FlightDescriptor: ... + @property + def endpoints(self) -> list[FlightEndpoint]: ... + @property + def total_records(self) -> int: ... + @property + def total_bytes(self) -> int: ... + @property + def ordered(self) -> bool: ... + @property + def app_metadata(self) -> bytes | str: ... + def serialize(self) -> bytes: ... + @classmethod + def deserialize(cls, serialized: bytes) -> Self: ... + +class FlightStreamChunk(_Weakrefable): + @property + def data(self) -> RecordBatch | None: ... + @property + def app_metadata(self) -> Buffer | None: ... + def __iter__(self) -> Iterator[RecordBatch | Buffer | None]: ... + +class _MetadataRecordBatchReader(_Weakrefable, _ReadPandasMixin): + # Needs to be separate class so the "real" class can subclass the + # pure-Python mixin class + + def __iter__(self) -> Self: ... + def __next__(self) -> FlightStreamChunk: ... + @property + def schema(self) -> Schema: ... + def read_all(self) -> Table: ... + def read_chunk(self) -> FlightStreamChunk: ... + def to_reader(self) -> RecordBatchReader: ... + +class MetadataRecordBatchReader(_MetadataRecordBatchReader): + @property + def stats(self) -> ReadStats: ... + +class FlightStreamReader(MetadataRecordBatchReader): + @property + def stats(self) -> ReadStats: ... + def cancel(self) -> None: ... + def read_all(self) -> Table: ... + +class MetadataRecordBatchWriter(_CRecordBatchWriter): + def begin(self, schema: Schema, options: IpcWriteOptions | None = None) -> None: ... + def write_metadata(self, buf: Buffer | bytes) -> None: ... + def write_batch(self, batch: RecordBatch) -> None: ... # type: ignore[override] + def write_table( + self, table: Table, max_chunksize: int | None = None, **kwargs: Any + ) -> None: ... + def close(self) -> None: ... + def write_with_metadata(self, batch: RecordBatch, buf: Buffer | bytes) -> None: ... + +class FlightStreamWriter(MetadataRecordBatchWriter): + def done_writing(self) -> None: ... + +class FlightMetadataReader(_Weakrefable): + def read(self) -> Buffer | None: ... + +class FlightMetadataWriter(_Weakrefable): + def write(self, message: Buffer) -> None: ... + +class AsyncioCall(Generic[_T]): + _future: asyncio.Future[_T] + + def as_awaitable(self) -> asyncio.Future[_T]: ... + def wakeup(self, result_or_exception: BaseException | _T) -> None: ... + +class AsyncioFlightClient: + def __init__(self, client: FlightClient) -> None: ... + async def get_flight_info( + self, + descriptor: FlightDescriptor, + *, + options: FlightCallOptions | None = None, + ) -> FlightInfo: ... + +class FlightClient(_Weakrefable): + def __init__( + self, + location: str | tuple[str, int] | Location, + *, + tls_root_certs: str | None = None, + cert_chain: str | None = None, + private_key: str | None = None, + override_hostname: str | None = None, + middleware: list[ClientMiddlewareFactory] | None = None, + write_size_limit_bytes: int | None = None, + disable_server_verification: bool | None = None, + generic_options: Sequence[tuple[str, int | str]] | None = None, + ) -> None: ... + @property + def supports_async(self) -> bool: ... + def as_async(self) -> AsyncioFlightClient: ... + def wait_for_available(self, timeout: int = 5) -> None: ... + @classmethod + @deprecated( + "Use the ``FlightClient`` constructor or " + "``pyarrow.flight.connect`` function instead." + ) + def connect( + cls, + location: str | tuple[str, int] | Location, + tls_root_certs: str | None = None, + cert_chain: str | None = None, + private_key: str | None = None, + override_hostname: str | None = None, + disable_server_verification: bool | None = None, + ) -> FlightClient: ... + def authenticate( + self, auth_handler: ClientAuthHandler, options: FlightCallOptions | None = None + ) -> None: ... + def authenticate_basic_token( + self, + username: str | bytes, + password: str | bytes, + options: FlightCallOptions | None = None, + ) -> tuple[str, str]: ... + def list_actions( + self, options: FlightCallOptions | None = None + ) -> list[Action]: ... + def do_action( + self, + action: Action | tuple[bytes | str, bytes | str] | str, + options: FlightCallOptions | None = None, + ) -> Iterator[Result]: ... + def list_flights( + self, + criteria: str | bytes | None = None, + options: FlightCallOptions | None = None, + ) -> Iterator[FlightInfo]: ... + def get_flight_info( + self, descriptor: FlightDescriptor, options: FlightCallOptions | None = None + ) -> FlightInfo: ... + def get_schema( + self, descriptor: FlightDescriptor, options: FlightCallOptions | None = None + ) -> SchemaResult: ... + def do_get( + self, ticket: Ticket, options: FlightCallOptions | None = None + ) -> FlightStreamReader: ... + def do_put( + self, + descriptor: FlightDescriptor, + schema: Schema | None, + options: FlightCallOptions | None = None, + ) -> tuple[FlightStreamWriter, FlightStreamReader]: ... + def do_exchange( + self, descriptor: FlightDescriptor, options: FlightCallOptions | None = None + ) -> tuple[FlightStreamWriter, FlightStreamReader]: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: object, exc_value: object, traceback: object + ) -> None: ... + +class FlightDataStream(_Weakrefable): ... + +class RecordBatchStream(FlightDataStream): + def __init__( + self, + data_source: RecordBatchReader | Table | None = None, + options: IpcWriteOptions | None = None, + ) -> None: ... + +class GeneratorStream(FlightDataStream): + def __init__( + self, + schema: Schema, + generator: Iterable[ + FlightDataStream + | Table + | RecordBatch + | RecordBatchReader + | tuple[RecordBatch, bytes] + ], + options: IpcWriteOptions | None = None, + ) -> None: ... + +class ServerCallContext(_Weakrefable): + def peer_identity(self) -> bytes: ... + def peer(self) -> str: ... + + # Set safe=True as gRPC on Windows sometimes gives garbage bytes + def is_cancelled(self) -> bool: ... + def add_header(self, key: str, value: str) -> None: ... + def add_trailer(self, key: str, value: str) -> None: ... + def get_middleware(self, key: str) -> ServerMiddleware | None: ... + +class ServerAuthReader(_Weakrefable): + def read(self) -> str: ... + +class ServerAuthSender(_Weakrefable): + def write(self, message: str) -> None: ... + +class ClientAuthReader(_Weakrefable): + def read(self) -> str: ... + +class ClientAuthSender(_Weakrefable): + def write(self, message: str) -> None: ... + +class ServerAuthHandler(_Weakrefable): + def authenticate( + self, outgoing: ServerAuthSender, incoming: ServerAuthReader + ) -> None: ... + def is_valid(self, token: str) -> bool: ... + +class ClientAuthHandler(_Weakrefable): + def authenticate( + self, outgoing: ClientAuthSender, incoming: ClientAuthReader + ) -> None: ... + def get_token(self) -> str: ... + +class CallInfo(NamedTuple): + method: FlightMethod + +class ClientMiddlewareFactory(_Weakrefable): + def start_call(self, info: CallInfo) -> ClientMiddleware | None: ... + +class ClientMiddleware(_Weakrefable): + def sending_headers(self) -> dict[str, list[str] | list[bytes]]: ... + def received_headers(self, headers: dict[str, list[str] | list[bytes]]) -> None: ... + def call_completed(self, exception: ArrowException) -> None: ... + +class ServerMiddlewareFactory(_Weakrefable): + def start_call( + self, info: CallInfo, headers: dict[str, list[str] | list[bytes]] + ) -> ServerMiddleware | None: ... + +class TracingServerMiddlewareFactory(ServerMiddlewareFactory): ... + +class ServerMiddleware(_Weakrefable): + def sending_headers(self) -> dict[str, list[str] | list[bytes]]: ... + def call_completed(self, exception: ArrowException) -> None: ... + +class TracingServerMiddleware(ServerMiddleware): + trace_context: dict[str, Any] + def __init__(self, trace_context: dict[str, Any]) -> None: ... + +class _ServerMiddlewareFactoryWrapper(ServerMiddlewareFactory): + def __init__(self, factories: dict[str, ServerMiddlewareFactory]) -> None: ... + def start_call( # type: ignore[override] + self, info: CallInfo, headers: dict[str, list[str] | list[bytes]] + ) -> _ServerMiddlewareFactoryWrapper | None: ... + +class _ServerMiddlewareWrapper(ServerMiddleware): + def __init__(self, middleware: dict[str, ServerMiddleware]) -> None: ... + def call_completed(self, exception: ArrowException) -> None: ... + +class _FlightServerFinalizer(_Weakrefable): + def finalize(self) -> None: ... + +class FlightServerBase(_Weakrefable): + def __init__( + self, + location: str | tuple[str, int] | Location | None = None, + auth_handler: ServerAuthHandler | None = None, + tls_certificates: list[tuple[str, str]] | None = None, + verify_client: bool = False, + root_certificates: str | None = None, + middleware: dict[str, ServerMiddlewareFactory] | None = None, + ) -> None: ... + @property + def port(self) -> int: ... + def list_flights( + self, context: ServerCallContext, criteria: str + ) -> Iterator[FlightInfo]: ... + def get_flight_info( + self, context: ServerCallContext, descriptor: FlightDescriptor + ) -> FlightInfo: ... + def get_schema( + self, context: ServerCallContext, descriptor: FlightDescriptor + ) -> Schema: ... + def do_put( + self, + context: ServerCallContext, + descriptor: FlightDescriptor, + reader: MetadataRecordBatchReader, + writer: FlightMetadataWriter, + ) -> None: ... + def do_get( + self, context: ServerCallContext, ticket: Ticket + ) -> FlightDataStream: ... + def do_exchange( + self, + context: ServerCallContext, + descriptor: FlightDescriptor, + reader: MetadataRecordBatchReader, + writer: MetadataRecordBatchWriter, + ) -> None: ... + def list_actions(self, context: ServerCallContext) -> Iterable[Action]: ... + def do_action( + self, context: ServerCallContext, action: Action + ) -> Iterable[bytes]: ... + def serve(self) -> None: ... + def run(self) -> None: ... + def shutdown(self) -> None: ... + def wait(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: object, exc_value: object, traceback: object + ) -> None: ... + +def connect( + location: str | tuple[str, int] | Location, + *, + tls_root_certs: str | None = None, + cert_chain: str | None = None, + private_key: str | None = None, + override_hostname: str | None = None, + middleware: list[ClientMiddlewareFactory] | None = None, + write_size_limit_bytes: int | None = None, + disable_server_verification: bool = False, + generic_options: Sequence[tuple[str, int | str]] | None = None, +) -> FlightClient: ... diff --git a/python/pyarrow-stubs/_fs.pyi b/python/pyarrow-stubs/_fs.pyi new file mode 100644 index 00000000000..47588410d94 --- /dev/null +++ b/python/pyarrow-stubs/_fs.pyi @@ -0,0 +1,183 @@ +# 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 +import enum +from abc import ABC, abstractmethod +from typing import TypeAlias, overload + +from _typeshed import StrPath +from fsspec import AbstractFileSystem + +from .lib import NativeFile, _Weakrefable + +class FileType(enum.IntFlag): + NotFound = 0 + Unknown = 1 + File = 2 + Directory = 3 + +class FileInfo(_Weakrefable): + def __init__( + self, + path: str, + type: FileType = ..., + *, + mtime: dt.datetime | float | None = None, + mtime_ns: int | None = None, + size: int | None = None, + ) -> None: ... + @property + def type(self) -> FileType: ... + @property + def is_file(self) -> bool: ... + @property + def path(self) -> str: ... + @property + def base_name(self) -> str: ... + @property + def size(self) -> int: ... + @property + def extension(self) -> str: ... + @property + def mtime(self) -> dt.datetime | None: ... + @property + def mtime_ns(self) -> int | None: ... + +class FileSelector(_Weakrefable): + base_dir: str + allow_not_found: bool + recursive: bool + def __init__( + self, base_dir: str, allow_not_found: bool = False, recursive: bool = False + ) -> None: ... + +class FileSystem(_Weakrefable): + @staticmethod + def from_uri(uri: str | StrPath) -> tuple[FileSystem, str]: ... + def equals(self, other: FileSystem | object) -> bool: ... + @property + def type_name(self) -> str: ... + @overload + def get_file_info(self, paths_or_selector: str) -> FileInfo: ... + @overload + def get_file_info( + self, paths_or_selector: list[str] | FileSelector + ) -> list[FileInfo]: ... + @overload + def get_file_info( + self, paths_or_selector: str | list[str] | FileSelector + ) -> FileInfo | list[FileInfo]: ... + def create_dir(self, path: str, *, recursive: bool = True) -> None: ... + def delete_dir(self, path: str) -> None: ... + def delete_dir_contents( + self, path: str, *, accept_root_dir: bool = False, missing_dir_ok: bool = False + ) -> None: ... + def move(self, src: str, dest: str) -> None: ... + def copy_file(self, src: str, dest: str) -> None: ... + def delete_file(self, path: str) -> None: ... + def open_input_file(self, path: str) -> NativeFile: ... + def open_input_stream( + self, + path: str, + compression: str | None = "detect", + buffer_size: int | None = None, + ) -> NativeFile: ... + def open_output_stream( + self, + path: str, + compression: str | None = "detect", + buffer_size: int | None = None, + metadata: dict[str, str] | None = None, + ) -> NativeFile: ... + def open_append_stream( + self, + path: str, + compression: str | None = "detect", + buffer_size: int | None = None, + metadata: dict[str, str] | None = None, + ) -> NativeFile: ... + def normalize_path(self, path: str) -> str: ... + +class LocalFileSystem(FileSystem): + def __init__(self, *, use_mmap: bool = False) -> None: ... + +class SubTreeFileSystem(FileSystem): + def __init__(self, base_path: str, base_fs: FileSystem) -> None: ... + @property + def base_path(self) -> str: ... + @property + def base_fs(self) -> FileSystem: ... + +class _MockFileSystem(FileSystem): + def __init__(self, current_time: dt.datetime | None = None) -> None: ... + +class PyFileSystem(FileSystem): + def __init__(self, handler: FileSystemHandler | None) -> None: ... + @property + def handler(self) -> FileSystemHandler: ... + +class FileSystemHandler(ABC): + @abstractmethod + def get_type_name(self) -> str: ... + @abstractmethod + def get_file_info(self, paths: str | list[str]) -> FileInfo | list[FileInfo]: ... + @abstractmethod + def get_file_info_selector(self, selector: FileSelector) -> list[FileInfo]: ... + @abstractmethod + def create_dir(self, path: str, recursive: bool) -> None: ... + @abstractmethod + def delete_dir(self, path: str) -> None: ... + @abstractmethod + def delete_dir_contents(self, path: str, missing_dir_ok: bool) -> None: ... + @abstractmethod + def delete_root_dir_contents(self) -> None: ... + @abstractmethod + def delete_file(self, path: str) -> None: ... + @abstractmethod + def move(self, src: str, dest: str) -> None: ... + @abstractmethod + def copy_file(self, src: str, dest: str) -> None: ... + @abstractmethod + def open_input_stream(self, path: str) -> NativeFile: ... + @abstractmethod + def open_input_file(self, path: str) -> NativeFile: ... + @abstractmethod + def open_output_stream(self, path: str, metadata: dict[str, str]) -> NativeFile: ... + @abstractmethod + def open_append_stream(self, path: str, metadata: dict[str, str]) -> NativeFile: ... + @abstractmethod + def normalize_path(self, path: str) -> str: ... + +_SupportedFileSystem: TypeAlias = AbstractFileSystem | FileSystem + +def _copy_files( + source_fs: FileSystem, + source_path: str, + destination_fs: _SupportedFileSystem | None, + destination_path: str, + chunk_size: int, + use_threads: bool, +) -> None: ... +def _copy_files_selector( + source_fs: FileSystem, + source_sel: FileSelector, + destination_fs: _SupportedFileSystem | None, + destination_base_dir: str, + chunk_size: int, + use_threads: bool, +) -> None: ... diff --git a/python/pyarrow-stubs/_gcsfs.pyi b/python/pyarrow-stubs/_gcsfs.pyi new file mode 100644 index 00000000000..ef1336b663a --- /dev/null +++ b/python/pyarrow-stubs/_gcsfs.pyi @@ -0,0 +1,41 @@ +# 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 ._fs import FileSystem +from .lib import KeyValueMetadata + +class GcsFileSystem(FileSystem): + def __init__( + self, + *, + anonymous: bool = False, + access_token: str | None = None, + target_service_account: str | None = None, + credential_token_expiration: dt.datetime | None = None, + default_bucket_location: str = "US", + scheme: str = "https", + endpoint_override: str | None = None, + default_metadata: dict[str, str] | KeyValueMetadata | None = None, + retry_time_limit: dt.timedelta | None = None, + project_id: str | None = None, + ) -> None: ... + @property + def default_bucket_location(self) -> str: ... + @property + def project_id(self) -> str: ... diff --git a/python/pyarrow-stubs/_hdfs.pyi b/python/pyarrow-stubs/_hdfs.pyi new file mode 100644 index 00000000000..db2a71680b0 --- /dev/null +++ b/python/pyarrow-stubs/_hdfs.pyi @@ -0,0 +1,36 @@ +# 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 _typeshed import StrPath + +from ._fs import FileSystem + +class HadoopFileSystem(FileSystem): + def __init__( + self, + host: str | None = None, + port: int = 8020, + *, + user: str | None = None, + replication: int = 3, + buffer_size: int = 0, + default_block_size: int | None = None, + kerb_ticket: StrPath | None = None, + extra_conf: dict[str, str] | None = None, + ) -> None: ... + @staticmethod + def from_uri(uri: str | int) -> HadoopFileSystem: ... # type: ignore[override] 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/_parquet.pyi b/python/pyarrow-stubs/_parquet.pyi new file mode 100644 index 00000000000..502d7266375 --- /dev/null +++ b/python/pyarrow-stubs/_parquet.pyi @@ -0,0 +1,463 @@ +# 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, Iterator, Sequence +from typing import IO, Any, Literal, TypeAlias, TypedDict + +from _typeshed import StrPath + +from ._stubs_typing import Order +from .lib import ( + Buffer, + ChunkedArray, + KeyValueMetadata, + MemoryPool, + NativeFile, + RecordBatch, + Schema, + Table, + _Weakrefable, + DataType, +) + +_PhysicalType: TypeAlias = Literal[ + "BOOLEAN", + "INT32", + "INT64", + "INT96", + "FLOAT", + "DOUBLE", + "BYTE_ARRAY", + "FIXED_LEN_BYTE_ARRAY", + "UNKNOWN", +] +_LogicTypeName: TypeAlias = Literal[ + "UNDEFINED", + "STRING", + "MAP", + "LIST", + "ENUM", + "DECIMAL", + "DATE", + "TIME", + "TIMESTAMP", + "INT", + "FLOAT16", + "JSON", + "BSON", + "UUID", + "NONE", + "UNKNOWN", +] +_ConvertedType: TypeAlias = Literal[ + "NONE", + "UTF8", + "MAP", + "MAP_KEY_VALUE", + "LIST", + "ENUM", + "DECIMAL", + "DATE", + "TIME_MILLIS", + "TIME_MICROS", + "TIMESTAMP_MILLIS", + "TIMESTAMP_MICROS", + "UINT_8", + "UINT_16", + "UINT_32", + "UINT_64", + "INT_8", + "INT_16", + "INT_32", + "INT_64", + "JSON", + "BSON", + "INTERVAL", + "UNKNOWN", +] +_Encoding: TypeAlias = Literal[ + "PLAIN", + "PLAIN_DICTIONARY", + "RLE", + "BIT_PACKED", + "DELTA_BINARY_PACKED", + "DELTA_LENGTH_BYTE_ARRAY", + "DELTA_BYTE_ARRAY", + "RLE_DICTIONARY", + "BYTE_STREAM_SPLIT", + "UNKNOWN", +] +_Compression: TypeAlias = Literal[ + "UNCOMPRESSED", + "SNAPPY", + "GZIP", + "LZO", + "BROTLI", + "LZ4", + "ZSTD", + "UNKNOWN", +] + +class _Statistics(TypedDict): + has_min_max: bool + min: Any | None + max: Any | None + null_count: int | None + distinct_count: int | None + num_values: int + physical_type: _PhysicalType + +class Statistics(_Weakrefable): + def to_dict(self) -> _Statistics: ... + def equals(self, other: Statistics) -> bool: ... + @property + def has_min_max(self) -> bool: ... + @property + def has_null_count(self) -> bool: ... + @property + def has_distinct_count(self) -> bool: ... + @property + def min_raw(self) -> Any | None: ... + @property + def max_raw(self) -> Any | None: ... + @property + def min(self) -> Any | None: ... + @property + def max(self) -> Any | None: ... + @property + def null_count(self) -> int | None: ... + @property + def distinct_count(self) -> int | None: ... + @property + def num_values(self) -> int: ... + @property + def physical_type(self) -> _PhysicalType: ... + @property + def logical_type(self) -> ParquetLogicalType: ... + @property + def converted_type(self) -> _ConvertedType | None: ... + +class GeoStatistics(_Weakrefable): + def to_dict(self) -> dict[str, Any]: ... + @property + def geospatial_types(self) -> list[int] | None: ... + @property + def xmin(self) -> float | None: ... + @property + def xmax(self) -> float | None: ... + @property + def ymin(self) -> float | None: ... + @property + def ymax(self) -> float | None: ... + @property + def zmin(self) -> float | None: ... + @property + def zmax(self) -> float | None: ... + @property + def mmin(self) -> float | None: ... + @property + def mmax(self) -> float | None: ... + +class ParquetLogicalType(_Weakrefable): + def to_json(self) -> str: ... + @property + def type(self) -> _LogicTypeName: ... + +class _ColumnChunkMetaData(TypedDict): + file_offset: int + file_path: str | None + physical_type: _PhysicalType + num_values: int + path_in_schema: str + is_stats_set: bool + statistics: Statistics | None + compression: _Compression + encodings: tuple[_Encoding, ...] + has_dictionary_page: bool + dictionary_page_offset: int | None + data_page_offset: int + total_compressed_size: int + total_uncompressed_size: int + +class ColumnChunkMetaData(_Weakrefable): + def to_dict(self) -> _ColumnChunkMetaData: ... + def equals(self, other: ColumnChunkMetaData) -> bool: ... + @property + def file_offset(self) -> int: ... + @property + def file_path(self) -> str | None: ... + @property + def physical_type(self) -> _PhysicalType: ... + @property + def num_values(self) -> int: ... + @property + def path_in_schema(self) -> str: ... + @property + def is_stats_set(self) -> bool: ... + @property + def statistics(self) -> Statistics | None: ... + @property + def is_geo_stats_set(self) -> bool: ... + @property + def geo_statistics(self) -> GeoStatistics | None: ... + @property + def compression(self) -> _Compression: ... + @property + def encodings(self) -> tuple[_Encoding, ...]: ... + @property + def has_dictionary_page(self) -> bool: ... + @property + def dictionary_page_offset(self) -> int | None: ... + @property + def data_page_offset(self) -> int: ... + @property + def has_index_page(self) -> bool: ... + @property + def index_page_offset(self) -> int: ... + @property + def total_compressed_size(self) -> int: ... + @property + def total_uncompressed_size(self) -> int: ... + @property + def has_offset_index(self) -> bool: ... + @property + def has_column_index(self) -> bool: ... + @property + def metadata(self) -> dict[bytes, bytes] | None: ... + +class _SortingColumn(TypedDict): + column_index: int + descending: bool + nulls_first: bool + +class SortingColumn: + def __init__( + self, column_index: int, descending: bool = False, nulls_first: bool = False + ) -> None: ... + @classmethod + def from_ordering( + cls, + schema: Schema, + sort_keys: Sequence[str] + | Sequence[tuple[str, Order]] + | Sequence[str | tuple[str, Order]], + null_placement: Literal["at_start", "at_end"] = "at_end", + ) -> tuple[SortingColumn, ...]: ... + @staticmethod + def to_ordering( + schema: Schema, sorting_columns: tuple[SortingColumn, ...] | list[SortingColumn] + ) -> tuple[Sequence[tuple[str, Order]], Literal["at_start", "at_end"]]: ... + def __hash__(self) -> int: ... + @property + def column_index(self) -> int: ... + @property + def descending(self) -> bool: ... + @property + def nulls_first(self) -> bool: ... + def to_dict(self) -> _SortingColumn: ... + +class _RowGroupMetaData(TypedDict): + num_columns: int + num_rows: int + total_byte_size: int + columns: list[ColumnChunkMetaData] + sorting_columns: list[SortingColumn] + +class RowGroupMetaData(_Weakrefable): + def __init__(self, parent: FileMetaData, index: int) -> None: ... + def equals(self, other: RowGroupMetaData) -> bool: ... + def column(self, i: int) -> ColumnChunkMetaData: ... + def to_dict(self) -> _RowGroupMetaData: ... + @property + def num_columns(self) -> int: ... + @property + def num_rows(self) -> int: ... + @property + def total_byte_size(self) -> int: ... + @property + def sorting_columns(self) -> list[SortingColumn]: ... + +class _FileMetaData(TypedDict): + created_by: str + num_columns: int + num_rows: int + num_row_groups: int + format_version: str + serialized_size: int + row_groups: list[Any] # List of row group metadata dictionaries + +class FileMetaData(_Weakrefable): + def __hash__(self) -> int: ... + def to_dict(self) -> _FileMetaData: ... + def equals(self, other: FileMetaData) -> bool: ... + @property + def schema(self) -> ParquetSchema: ... + @property + def serialized_size(self) -> int: ... + @property + def num_columns(self) -> int: ... + @property + def num_rows(self) -> int: ... + @property + def num_row_groups(self) -> int: ... + @property + def format_version(self) -> str: ... + @property + def created_by(self) -> str: ... + @property + def metadata(self) -> dict[bytes, bytes] | None: ... + def row_group(self, i: int) -> RowGroupMetaData: ... + def set_file_path(self, path: str) -> None: ... + def append_row_groups(self, other: FileMetaData) -> None: ... + def write_metadata_file( + self, where: StrPath | Buffer | NativeFile | IO[Any] + ) -> None: ... + +class ParquetSchema(_Weakrefable): + def __init__(self, container: FileMetaData) -> None: ... + def __getitem__(self, i: int, /) -> ColumnSchema: ... + def __hash__(self) -> int: ... + def __len__(self) -> int: ... + @property + def names(self) -> list[str]: ... + def to_arrow_schema(self) -> Schema: ... + def equals(self, other: ParquetSchema) -> bool: ... + def column(self, i: int) -> ColumnSchema: ... + +class ColumnSchema(_Weakrefable): + def __init__(self, schema: ParquetSchema, index: int) -> None: ... + def equals(self, other: ColumnSchema) -> bool: ... + @property + def name(self) -> str: ... + @property + def path(self) -> str: ... + @property + def max_definition_level(self) -> int: ... + @property + def max_repetition_level(self) -> int: ... + @property + def physical_type(self) -> _PhysicalType: ... + @property + def logical_type(self) -> ParquetLogicalType: ... + @property + def converted_type(self) -> _ConvertedType | None: ... + @property + def length(self) -> int | None: ... + @property + def precision(self) -> int | None: ... + @property + def scale(self) -> int | None: ... + +class ParquetReader(_Weakrefable): + def __init__(self, memory_pool: MemoryPool | None = None) -> None: ... + def open( + self, + source: StrPath | Buffer | NativeFile | IO[Any], + *, + use_memory_map: bool = False, + read_dictionary: Iterable[int] | Iterable[str] | None = None, + metadata: FileMetaData | None = None, + binary_type: DataType | None = None, + list_type: DataType | None = None, + buffer_size: int = 0, + pre_buffer: bool = False, + coerce_int96_timestamp_unit: str | None = None, + decryption_properties: FileDecryptionProperties | None = None, + thrift_string_size_limit: int | None = None, + thrift_container_size_limit: int | None = None, + page_checksum_verification: bool = False, + arrow_extensions_enabled: bool = False, + ) -> None: ... + @property + def column_paths(self) -> list[str]: ... + @property + def metadata(self) -> FileMetaData: ... + @property + def schema_arrow(self) -> Schema: ... + @property + def num_row_groups(self) -> int: ... + def set_use_threads(self, use_threads: bool) -> None: ... + def set_batch_size(self, batch_size: int) -> None: ... + def iter_batches( + self, + batch_size: int, + row_groups: list[int] | range, + column_indices: list[str] | list[int] | None = None, + use_threads: bool = True, + ) -> Iterator[RecordBatch]: ... + def read_row_group( + self, i: int, column_indices: list[int] | None = None, use_threads: bool = True + ) -> Table: ... + def read_row_groups( + self, + row_groups: Sequence[int] | range, + column_indices: list[str] | list[int] | None = None, + use_threads: bool = True, + ) -> Table: ... + def read_all( + self, column_indices: list[int] | None = None, use_threads: bool = True + ) -> Table: ... + def scan_contents( + self, + column_indices: Sequence[str] | Sequence[int] | None = None, + batch_size: int = 65536, + ) -> int: ... + def column_name_idx(self, column_name: str) -> int: ... + def read_column(self, column_index: int) -> ChunkedArray: ... + def close(self) -> None: ... + @property + def closed(self) -> bool: ... + +class ParquetWriter(_Weakrefable): + def __init__( + self, + where: StrPath | NativeFile | IO[Any], + schema: Schema, + use_dictionary: bool | list[str] | None = None, + compression: _Compression | dict[str, _Compression] | str | None = None, + version: str | None = None, + write_statistics: bool | list[str] | None = None, + memory_pool: MemoryPool | None = None, + use_deprecated_int96_timestamps: bool = False, + coerce_timestamps: Literal["ms", "us"] | None = None, + data_page_size: int | None = None, + allow_truncated_timestamps: bool = False, + compression_level: int | dict[str, int] | None = None, + use_byte_stream_split: bool | list[str] = False, + column_encoding: _Encoding | dict[str, _Encoding] | None = None, + writer_engine_version: str | None = None, + data_page_version: str | None = None, + use_compliant_nested_type: bool = True, + encryption_properties: FileDecryptionProperties | None = None, + write_batch_size: int | None = None, + dictionary_pagesize_limit: int | None = None, + store_schema: bool = True, + write_page_index: bool = False, + write_page_checksum: bool = False, + sorting_columns: tuple[SortingColumn, ...] | None = None, + store_decimal_as_integer: bool = False, + write_time_adjusted_to_utc: bool = False, + max_rows_per_page: int | None = None, + ) -> None: ... + def close(self) -> None: ... + def write_table(self, table: Table, row_group_size: int | None = None) -> None: ... + def add_key_value_metadata(self, key_value_metadata: KeyValueMetadata) -> None: ... + @property + def metadata(self) -> FileMetaData: ... + +class FileEncryptionProperties: ... +class FileDecryptionProperties: ... diff --git a/python/pyarrow-stubs/_parquet_encryption.pyi b/python/pyarrow-stubs/_parquet_encryption.pyi new file mode 100644 index 00000000000..180981629dd --- /dev/null +++ b/python/pyarrow-stubs/_parquet_encryption.pyi @@ -0,0 +1,149 @@ +# 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 +import pathlib + +from collections.abc import Callable + +from pyarrow._fs import FileSystem +from ._parquet import FileDecryptionProperties, FileEncryptionProperties +from .lib import _Weakrefable + +class EncryptionConfiguration(_Weakrefable): + footer_key: str + column_keys: dict[str, list[str]] + encryption_algorithm: str + plaintext_footer: bool + double_wrapping: bool + cache_lifetime: dt.timedelta + internal_key_material: bool + data_key_length_bits: int + uniform_encryption: bool + + def __init__( + self, + footer_key: str, + *, + column_keys: dict[str, str | list[str]] | None = None, + encryption_algorithm: str | None = None, + plaintext_footer: bool | None = None, + double_wrapping: bool | None = None, + cache_lifetime: dt.timedelta | None = None, + internal_key_material: bool | None = None, + data_key_length_bits: int | None = None, + uniform_encryption: bool | None = None, + ) -> None: ... + +class DecryptionConfiguration(_Weakrefable): + cache_lifetime: dt.timedelta + def __init__(self, *, cache_lifetime: dt.timedelta | None = None) -> None: ... + +class KmsConnectionConfig(_Weakrefable): + kms_instance_id: str + kms_instance_url: str + key_access_token: str + custom_kms_conf: dict[str, str] + + def __init__( + self, + *, + kms_instance_id: str | None = None, + kms_instance_url: str | None = None, + key_access_token: str | None = None, + custom_kms_conf: dict[str, str] | None = None, + ) -> None: ... + def refresh_key_access_token(self, value: str) -> None: ... + +class KmsClient(_Weakrefable): + def wrap_key(self, key_bytes: bytes, master_key_identifier: str) -> str: ... + def unwrap_key(self, wrapped_key: str, master_key_identifier: str) -> bytes: ... + +class CryptoFactory(_Weakrefable): + def __init__( + self, kms_client_factory: Callable[[KmsConnectionConfig], KmsClient] + ) -> None: ... + def file_encryption_properties( + self, + kms_connection_config: KmsConnectionConfig, + encryption_config: EncryptionConfiguration, + parquet_file_path: str | pathlib.Path | None = None, + filesystem: FileSystem | None = None, + ) -> FileEncryptionProperties: ... + def file_decryption_properties( + self, + kms_connection_config: KmsConnectionConfig, + decryption_config: DecryptionConfiguration | None = None, + parquet_file_path: str | pathlib.Path | None = None, + filesystem: FileSystem | None = None, + ) -> FileDecryptionProperties: ... + def remove_cache_entries_for_token(self, access_token: str) -> None: ... + def remove_cache_entries_for_all_tokens(self) -> None: ... + def rotate_master_keys( + self, + kms_connection_config: KmsConnectionConfig, + parquet_file_path: str | pathlib.Path, + filesystem: FileSystem | None = None, + double_wrapping: bool = True, + cache_lifetime_seconds: float = 600, + ) -> None: ... + +class KeyMaterial(_Weakrefable): + @property + def is_footer_key(self) -> bool: ... + @property + def is_double_wrapped(self) -> bool: ... + @property + def master_key_id(self) -> str: ... + @property + def wrapped_dek(self) -> str: ... + @property + def kek_id(self) -> str: ... + @property + def wrapped_kek(self) -> str: ... + @property + def kms_instance_id(self) -> str: ... + @property + def kms_instance_url(self) -> str: ... + @staticmethod + def parse(key_material_string: str) -> KeyMaterial: ... + +class FileSystemKeyMaterialStore(_Weakrefable): + def get_key_material(self, key_id: str) -> KeyMaterial: ... + def get_key_id_set(self) -> list[str]: ... + @classmethod + def for_file( + cls, + parquet_file_path: str | pathlib.Path, + filesystem: FileSystem | None = None, + ) -> FileSystemKeyMaterialStore: ... + +def create_encryption_properties( + footer_key: bytes, + *, + aad_prefix: bytes | None = None, + store_aad_prefix: bool = True, + encryption_algorithm: str = "AES_GCM_V1", + plaintext_footer: bool = False, +) -> FileEncryptionProperties: ... +def create_decryption_properties( + footer_key: bytes, + *, + aad_prefix: bytes | None = None, + check_footer_integrity: bool = True, + allow_plaintext_files: bool = False, +) -> FileDecryptionProperties: ... diff --git a/python/pyarrow-stubs/_s3fs.pyi b/python/pyarrow-stubs/_s3fs.pyi new file mode 100644 index 00000000000..b7008b49910 --- /dev/null +++ b/python/pyarrow-stubs/_s3fs.pyi @@ -0,0 +1,90 @@ +# 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 enum + +from typing import Any, Literal, TypedDict +from typing_extensions import Required, NotRequired + +from ._fs import FileSystem +from .lib import KeyValueMetadata + +class _ProxyOptions(TypedDict): + scheme: Required[Literal["http", "https"]] + host: Required[str] + port: Required[int] + username: NotRequired[str] + password: NotRequired[str] + +class S3LogLevel(enum.IntEnum): + Off = 0 + Fatal = 1 + Error = 2 + Warn = 3 + Info = 4 + Debug = 5 + Trace = 6 + +def initialize_s3( + log_level: S3LogLevel = ..., num_event_loop_threads: int = 1 +) -> None: ... +def ensure_s3_initialized() -> None: ... +def finalize_s3() -> None: ... +def ensure_s3_finalized() -> None: ... +def resolve_s3_region(bucket: str) -> str: ... + +class S3RetryStrategy: + max_attempts: int + def __init__(self, max_attempts: int = 3) -> None: ... + +class AwsStandardS3RetryStrategy(S3RetryStrategy): ... +class AwsDefaultS3RetryStrategy(S3RetryStrategy): ... + +class S3FileSystem(FileSystem): + def __init__( + self, + *, + access_key: str | None = None, + secret_key: str | None = None, + session_token: str | None = None, + anonymous: bool = False, + region: str | None = None, + request_timeout: float | None = None, + connect_timeout: float | None = None, + scheme: Literal["http", "https"] = "https", + endpoint_override: str | None = None, + background_writes: bool = True, + default_metadata: dict[Any, Any] | list[Any] | KeyValueMetadata | None = None, + role_arn: str | None = None, + session_name: str | None = None, + external_id: str | None = None, + load_frequency: int = 900, + proxy_options: _ProxyOptions + | dict[Any, Any] + | tuple[Any, ...] + | str + | None = None, + allow_bucket_creation: bool = False, + allow_bucket_deletion: bool = False, + allow_delayed_open: bool = False, + check_directory_existence_before_creation: bool = False, + tls_ca_file_path: str | None = None, + retry_strategy: S3RetryStrategy = ..., + force_virtual_addressing: bool = False, + ) -> None: ... + @property + def region(self) -> str: ... diff --git a/python/pyarrow-stubs/_stubs_typing.pyi b/python/pyarrow-stubs/_stubs_typing.pyi index 17ee2cffc31..f4db088e866 100644 --- a/python/pyarrow-stubs/_stubs_typing.pyi +++ b/python/pyarrow-stubs/_stubs_typing.pyi @@ -15,8 +15,8 @@ # specific language governing permissions and limitations # under the License. -from collections.abc import Sequence -from typing import Any, Literal, Protocol, TypeAlias +from collections.abc import Collection, Sequence +from typing import Any, Literal, Protocol, TypeAlias, TypeVar import numpy as np from numpy.typing import NDArray @@ -24,6 +24,26 @@ from pyarrow.lib import Array, ChunkedArray from pyarrow import lib +_T = TypeVar("_T") +SingleOrList: TypeAlias = list[_T] | _T + +Compression: TypeAlias = Literal[ + "gzip", "bz2", "brotli", "lz4", "lz4_frame", "lz4_raw", "zstd", "snappy" +] +JoinType: TypeAlias = Literal[ + "left semi", + "right semi", + "left anti", + "right anti", + "inner", + "left outer", + "right outer", + "full outer", +] +FilterTuple: TypeAlias = ( + tuple[str, Literal["=", "==", "!=", "<", ">", "<=", ">="], Any] + | tuple[str, Literal["in", "not in"], Collection[Any]] +) Order: TypeAlias = Literal["ascending", "descending"] MapsAsPydicts: TypeAlias = Literal["lossy", "strict"] NullEncoding: TypeAlias = Literal["mask", "encode"] @@ -36,6 +56,9 @@ Indices: TypeAlias = ( Sequence[int | None] | NDArray[np.integer[Any]] | Array | ChunkedArray ) +class SupportPyBuffer(Protocol): + def __buffer__(self, flags: int, /) -> memoryview: ... + class SupportsArrowStream(Protocol): def __arrow_c_stream__(self, requested_schema: Any = None, /) -> Any: ... diff --git a/python/pyarrow-stubs/_substrait.pyi b/python/pyarrow-stubs/_substrait.pyi new file mode 100644 index 00000000000..dc1cc5664cb --- /dev/null +++ b/python/pyarrow-stubs/_substrait.pyi @@ -0,0 +1,57 @@ +# 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 +from typing import Any + +from ._compute import Expression +from .lib import Buffer, RecordBatchReader, Schema, Table, _Weakrefable + +def run_query( + plan: Buffer | int, + *, + table_provider: Callable[[list[str], Schema], Table] | None = None, + use_threads: bool = True, +) -> RecordBatchReader: ... +def _parse_json_plan(plan: bytes) -> Buffer: ... + +class SubstraitSchema: + schema: bytes + expression: bytes + def __init__(self, schema: bytes, expression: bytes) -> None: ... + def to_pysubstrait(self) -> Any: ... + +def serialize_schema(schema: Schema) -> SubstraitSchema: ... +def deserialize_schema(buf: Buffer | bytes | SubstraitSchema) -> Schema: ... +def serialize_expressions( + exprs: list[Expression], + names: list[str], + schema: Schema, + *, + allow_arrow_extensions: bool = False, +) -> Buffer: ... + +class BoundExpressions(_Weakrefable): + @property + def schema(self) -> Schema: ... + @property + def expressions(self) -> dict[str, Expression]: ... + @classmethod + def from_substrait(cls, message: Buffer | bytes | Any) -> BoundExpressions: ... + +def deserialize_expressions(buf: Buffer | bytes) -> BoundExpressions: ... +def get_supported_functions() -> list[str]: ... diff --git a/python/pyarrow-stubs/cffi.pyi b/python/pyarrow-stubs/cffi.pyi new file mode 100644 index 00000000000..e4f077d7155 --- /dev/null +++ b/python/pyarrow-stubs/cffi.pyi @@ -0,0 +1,21 @@ +# 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 cffi + +c_source: str +ffi: cffi.FFI diff --git a/python/pyarrow-stubs/compute.pyi b/python/pyarrow-stubs/compute.pyi new file mode 100644 index 00000000000..dc0f690e874 --- /dev/null +++ b/python/pyarrow-stubs/compute.pyi @@ -0,0 +1,1710 @@ +# 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 Callable, Hashable, Sequence +from decimal import Decimal +from typing import Any, ParamSpec, TypeAlias, TypeVar + +import numpy as np +from numpy.typing import NDArray + +# Placeholders (Any) until scalar.pyi is annotated; mypy rejects them as +# types when imported through pyarrow.lib. +from pyarrow.__lib.scalar import ( + BinaryScalar, + BinaryViewScalar, + BooleanScalar, + Date32Scalar, + Date64Scalar, + Decimal32Scalar, + Decimal64Scalar, + Decimal128Scalar, + Decimal256Scalar, + DoubleScalar, + DurationScalar, + FixedSizeBinaryScalar, + FixedSizeListScalar, + FloatScalar, + HalfFloatScalar, + Int8Scalar, + Int16Scalar, + Int32Scalar, + Int64Scalar, + LargeBinaryScalar, + LargeListScalar, + LargeListViewScalar, + LargeStringScalar, + ListScalar, + ListViewScalar, + MonthDayNanoIntervalScalar, + Scalar, + StringScalar, + StringViewScalar, + StructScalar, + Time32Scalar, + Time64Scalar, + TimestampScalar, + UInt8Scalar, + UInt16Scalar, + UInt32Scalar, + UInt64Scalar, +) +from pyarrow._compute import ( + ArraySortOptions as ArraySortOptions, + AssumeTimezoneOptions as AssumeTimezoneOptions, + 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, + Order, + TimeUnit, +) +from pyarrow.lib import ( + Array, + BaseListArray, + BinaryArray, + BinaryViewArray, + BooleanArray, + ChunkedArray, + DataType, + Date32Array, + Date64Array, + Decimal32Array, + Decimal64Array, + Decimal128Array, + Decimal256Array, + DictionaryArray, + DoubleArray, + DurationArray, + FixedSizeBinaryArray, + FloatingPointArray, + Int32Array, + Int64Array, + IntegerArray, + KeyValueMetadata, + LargeBinaryArray, + LargeStringArray, + MemoryPool, + MonthDayNanoIntervalArray, + NumericArray, + RecordBatch, + RunEndEncodedArray, + StringArray, + StringViewArray, + StructArray, + Table, + Time32Array, + Time64Array, + TimestampArray, + UInt64Array, +) + +_P = ParamSpec("_P") +_R = TypeVar("_R") + +# Stub-only helper: the compute functions that share a signature are +# annotated once and the others are declared as copies of it. +def _clone_signature(f: Callable[_P, _R]) -> Callable[_P, _R]: ... +def field(*name_or_index: str | bytes | tuple[str | int, ...] | int) -> Expression: ... +def scalar(value: Any) -> Expression: ... + +# The inputs and outputs of the compute functions, by kind of data. The +# scalar classes are placeholders (Any) until scalar.pyi is annotated. +_SignedIntegerScalar: TypeAlias = Int8Scalar | Int16Scalar | Int32Scalar | Int64Scalar +_UnsignedIntegerScalar: TypeAlias = ( + UInt8Scalar | UInt16Scalar | UInt32Scalar | UInt64Scalar +) +_IntegerScalar: TypeAlias = _SignedIntegerScalar | _UnsignedIntegerScalar +_FloatScalar: TypeAlias = HalfFloatScalar | FloatScalar | DoubleScalar +_DecimalScalar: TypeAlias = ( + Decimal32Scalar | Decimal64Scalar | Decimal128Scalar | Decimal256Scalar +) +_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. An int is +# accepted where a float is. np.generic covers NumPy scalars. +_NumericLiteral: TypeAlias = float | Decimal | np.generic +_TemporalLiteral: TypeAlias = dt.date | dt.time | dt.timedelta | np.generic +_Literal: TypeAlias = _NumericLiteral | _TemporalLiteral | bool | str | bytes +_DecimalArray: TypeAlias = ( + Decimal32Array | Decimal64Array | Decimal128Array | Decimal256Array +) +# 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 + | ChunkedArray + | DoubleArray + | _FloatScalar + | DoubleScalar + | 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, + /, + 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, + /, + 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, + /, + *, + 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, + /, + *, + nan_is_null: bool = False, + options: NullOptions | None = None, + memory_pool: MemoryPool | None = None, +) -> BooleanScalar | BooleanArray | ChunkedArray | Expression: ... +def is_valid( + values: _ComputeInput, + /, + *, + 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, + 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, + /, + 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 ========================= +# TODO(GH-29828): add once PyArrow supports DayTimeInterval type +# def day_time_interval_between( +# start: _ComputeInput | _TemporalLiteral, +# end: _ComputeInput | _TemporalLiteral, +# /, +# *, +# memory_pool: MemoryPool | None = None, +# ) -> _ScalarOrArray | Expression: ... +def days_between( + start: _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 +): ... + +# TODO(GH-29828): add once PyArrow supports MonthInterval type +# def month_interval_between( +# start: _ComputeInput | _TemporalLiteral, +# end: _ComputeInput | _TemporalLiteral, +# /, +# *, +# memory_pool: MemoryPool | None = None, +# ) -> _ScalarOrArray | Expression: ... + +nanoseconds_between = _clone_signature(days_between) +quarters_between = _clone_signature(days_between) +seconds_between = _clone_signature(days_between) + +def weeks_between( + start: _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/cuda.pyi b/python/pyarrow-stubs/cuda.pyi new file mode 100644 index 00000000000..0394965bb73 --- /dev/null +++ b/python/pyarrow-stubs/cuda.pyi @@ -0,0 +1,42 @@ +# 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._cuda import ( + BufferReader, + BufferWriter, + Context, + CudaBuffer, + HostBuffer, + IpcMemHandle, + new_host_buffer, + read_message, + read_record_batch, + serialize_record_batch, +) + +__all__ = [ + "BufferReader", + "BufferWriter", + "Context", + "CudaBuffer", + "HostBuffer", + "IpcMemHandle", + "new_host_buffer", + "read_message", + "read_record_batch", + "serialize_record_batch", +] diff --git a/python/pyarrow-stubs/dataset.pyi b/python/pyarrow-stubs/dataset.pyi new file mode 100644 index 00000000000..740a010c6f4 --- /dev/null +++ b/python/pyarrow-stubs/dataset.pyi @@ -0,0 +1,200 @@ +# 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, Iterable, Sequence +from typing import Literal, TypeAlias, Any + +from _typeshed import StrPath +from pyarrow._dataset import ( + CsvFileFormat, + CsvFragmentScanOptions, + Dataset, + DatasetFactory, + DirectoryPartitioning, + FeatherFileFormat, + FileFormat, + FileFragment, + FilenamePartitioning, + FileSystemDataset, + FileSystemDatasetFactory, + FileSystemFactoryOptions, + FileWriteOptions, + FilteredDataset, + FilteredFragment, + Fragment, + FragmentScanOptions, + HivePartitioning, + InMemoryDataset, + IpcFileFormat, + IpcFileWriteOptions, + JsonFileFormat, + JsonFragmentScanOptions, + Partitioning, + PartitioningFactory, + Scanner, + TaggedRecordBatch, + UnionDataset, + UnionDatasetFactory, + WrittenFile, + get_partition_keys, +) +from pyarrow._dataset_orc import OrcFileFormat +from pyarrow._dataset_parquet import ( + ParquetDatasetFactory, + ParquetFactoryOptions, + ParquetFileFormat, + ParquetFileFragment, + ParquetFileWriteOptions, + ParquetFragmentScanOptions, + ParquetReadOptions, + RowGroupInfo, +) +from pyarrow._dataset_parquet_encryption import ( + ParquetDecryptionConfig, + ParquetEncryptionConfig, +) +from pyarrow.compute import Expression, field, scalar +from pyarrow.lib import Array, RecordBatch, RecordBatchReader, Schema, Table + +from ._fs import _SupportedFileSystem + +_orc_available: bool +_parquet_available: bool + +__all__ = [ + "CsvFileFormat", + "CsvFragmentScanOptions", + "Dataset", + "DatasetFactory", + "DirectoryPartitioning", + "FeatherFileFormat", + "FileFormat", + "FileFragment", + "FilenamePartitioning", + "FileSystemDataset", + "FileSystemDatasetFactory", + "FileSystemFactoryOptions", + "FileWriteOptions", + "FilteredDataset", + "FilteredFragment", + "Fragment", + "FragmentScanOptions", + "HivePartitioning", + "InMemoryDataset", + "IpcFileFormat", + "IpcFileWriteOptions", + "JsonFileFormat", + "JsonFragmentScanOptions", + "Partitioning", + "PartitioningFactory", + "Scanner", + "TaggedRecordBatch", + "UnionDataset", + "UnionDatasetFactory", + "WrittenFile", + "get_partition_keys", + # Orc + "OrcFileFormat", + # Parquet + "ParquetDatasetFactory", + "ParquetFactoryOptions", + "ParquetFileFormat", + "ParquetFileFragment", + "ParquetFileWriteOptions", + "ParquetFragmentScanOptions", + "ParquetReadOptions", + "RowGroupInfo", + # Parquet Encryption + "ParquetDecryptionConfig", + "ParquetEncryptionConfig", + # Compute + "Expression", + "field", + "scalar", + # Dataset + "partitioning", + "parquet_dataset", + "write_dataset", +] + +_DatasetFormat: TypeAlias = Literal[ + "parquet", "ipc", "arrow", "feather", "csv", "json", "orc" +] + +def partitioning( + schema: Schema | None = None, + field_names: list[str] | None = None, + flavor: Literal["hive"] | None = None, + dictionaries: dict[str, Array] | Literal["infer"] | None = None, +) -> Partitioning | PartitioningFactory: ... +def parquet_dataset( + metadata_path: StrPath, + schema: Schema | None = None, + filesystem: _SupportedFileSystem | None = None, + format: ParquetFileFormat | None = None, + partitioning: Partitioning | PartitioningFactory | str | None = None, + partition_base_dir: str | None = None, +) -> FileSystemDataset: ... +def dataset( + source: StrPath + | Sequence[Dataset] + | Sequence[StrPath] + | Iterable[RecordBatch] + | Iterable[Table] + | RecordBatchReader + | RecordBatch + | Table, + schema: Schema | None = None, + format: FileFormat | _DatasetFormat | None = None, + filesystem: _SupportedFileSystem | str | None = None, + partitioning: Partitioning | PartitioningFactory | str | list[str] | None = None, + partition_base_dir: str | None = None, + exclude_invalid_files: bool | None = None, + ignore_prefixes: list[str] | None = None, +) -> FileSystemDataset | UnionDataset | InMemoryDataset | Dataset: ... +def write_dataset( + data: Any + | Dataset + | Table + | RecordBatch + | RecordBatchReader + | list[Table] + | Iterable[RecordBatch] + | Scanner, + base_dir: StrPath, + *, + basename_template: str | None = None, + format: FileFormat | _DatasetFormat | None = None, + partitioning: Partitioning | PartitioningFactory | list[str] | None = None, + partitioning_flavor: str | None = None, + schema: Schema | None = None, + filesystem: _SupportedFileSystem | str | None = None, + file_options: FileWriteOptions | None = None, + use_threads: bool | None = True, + max_partitions: int | None = None, + max_open_files: int | None = None, + max_rows_per_file: int | None = None, + min_rows_per_group: int | None = None, + max_rows_per_group: int | None = None, + file_visitor: Callable[[str], None] | None = None, + existing_data_behavior: Literal[ + "error", "overwrite_or_ignore", "delete_matching" + ] = "error", + create_dir: bool = True, + preserve_order: bool = False, +) -> None: ... +def _get_partition_keys(partition_expression: Expression) -> dict[str, Any]: ... 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/flight.pyi b/python/pyarrow-stubs/flight.pyi new file mode 100644 index 00000000000..dcc6ee2244b --- /dev/null +++ b/python/pyarrow-stubs/flight.pyi @@ -0,0 +1,112 @@ +# 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._flight import ( + Action, + ActionType, + BasicAuth, + CallInfo, + CertKeyPair, + ClientAuthHandler, + ClientMiddleware, + ClientMiddlewareFactory, + DescriptorType, + FlightCallOptions, + FlightCancelledError, + FlightClient, + FlightDataStream, + FlightDescriptor, + FlightEndpoint, + FlightError, + FlightInfo, + FlightInternalError, + FlightMetadataReader, + FlightMetadataWriter, + FlightMethod, + FlightServerBase, + FlightServerError, + FlightStreamChunk, + FlightStreamReader, + FlightStreamWriter, + FlightTimedOutError, + FlightUnauthenticatedError, + FlightUnauthorizedError, + FlightUnavailableError, + FlightWriteSizeExceededError, + GeneratorStream, + Location, + MetadataRecordBatchReader, + MetadataRecordBatchWriter, + RecordBatchStream, + Result, + SchemaResult, + ServerAuthHandler, + ServerCallContext, + ServerMiddleware, + ServerMiddlewareFactory, + Ticket, + TracingServerMiddlewareFactory, + connect, +) + +__all__ = [ + "Action", + "ActionType", + "BasicAuth", + "CallInfo", + "CertKeyPair", + "ClientAuthHandler", + "ClientMiddleware", + "ClientMiddlewareFactory", + "DescriptorType", + "FlightCallOptions", + "FlightCancelledError", + "FlightClient", + "FlightDataStream", + "FlightDescriptor", + "FlightEndpoint", + "FlightError", + "FlightInfo", + "FlightInternalError", + "FlightMetadataReader", + "FlightMetadataWriter", + "FlightMethod", + "FlightServerBase", + "FlightServerError", + "FlightStreamChunk", + "FlightStreamReader", + "FlightStreamWriter", + "FlightTimedOutError", + "FlightUnauthenticatedError", + "FlightUnauthorizedError", + "FlightUnavailableError", + "FlightWriteSizeExceededError", + "GeneratorStream", + "Location", + "MetadataRecordBatchReader", + "MetadataRecordBatchWriter", + "RecordBatchStream", + "Result", + "SchemaResult", + "ServerAuthHandler", + "ServerCallContext", + "ServerMiddleware", + "ServerMiddlewareFactory", + "Ticket", + "TracingServerMiddlewareFactory", + "connect", +] diff --git a/python/pyarrow-stubs/fs.pyi b/python/pyarrow-stubs/fs.pyi new file mode 100644 index 00000000000..b33e40f3da3 --- /dev/null +++ b/python/pyarrow-stubs/fs.pyi @@ -0,0 +1,70 @@ +# 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._azurefs import AzureFileSystem as AzureFileSystem +from pyarrow._fs import ( + FileInfo as FileInfo, + FileSelector as FileSelector, + FileSystem as FileSystem, + FileSystemHandler as FileSystemHandler, + FileType as FileType, + LocalFileSystem as LocalFileSystem, + PyFileSystem as PyFileSystem, + SubTreeFileSystem as SubTreeFileSystem, + _MockFileSystem as _MockFileSystem, + _SupportedFileSystem, +) +from pyarrow._gcsfs import GcsFileSystem as GcsFileSystem +from pyarrow._hdfs import HadoopFileSystem as HadoopFileSystem +from pyarrow._s3fs import ( + AwsDefaultS3RetryStrategy as AwsDefaultS3RetryStrategy, + AwsStandardS3RetryStrategy as AwsStandardS3RetryStrategy, + S3FileSystem as S3FileSystem, + S3LogLevel as S3LogLevel, + S3RetryStrategy as S3RetryStrategy, + ensure_s3_finalized as ensure_s3_finalized, + ensure_s3_initialized as ensure_s3_initialized, + finalize_s3 as finalize_s3, + initialize_s3 as initialize_s3, + resolve_s3_region as resolve_s3_region, +) + +FileStats = FileInfo + +def copy_files( + source: str, + destination: str, + source_filesystem: _SupportedFileSystem | None = None, + destination_filesystem: _SupportedFileSystem | None = None, + *, + chunk_size: int = ..., + use_threads: bool = True, +) -> None: ... +def _ensure_filesystem( + filesystem: FileSystem | str | object, *, use_mmap: bool = False +) -> FileSystem: ... +def _resolve_filesystem_and_path( + path: str | object, + filesystem: FileSystem | str | object | None = None, + *, + memory_map: bool = False, +) -> tuple[FileSystem, str]: ... + +# All abstract methods are implemented via fsspec delegation. +class FSSpecHandler(FileSystemHandler): # type: ignore[misc] + fs: _SupportedFileSystem + def __init__(self, fs: _SupportedFileSystem) -> None: ... diff --git a/python/pyarrow-stubs/gandiva.pyi b/python/pyarrow-stubs/gandiva.pyi new file mode 100644 index 00000000000..0fae64c1500 --- /dev/null +++ b/python/pyarrow-stubs/gandiva.pyi @@ -0,0 +1,97 @@ +# 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, Sequence +from typing import Any, Literal + +from .lib import Array, DataType, Field, MemoryPool, RecordBatch, Schema, _Weakrefable + +class Node(_Weakrefable): + def return_type(self) -> DataType: ... + +class Expression(_Weakrefable): + def root(self) -> Node: ... + def result(self) -> Field: ... + +class Condition(_Weakrefable): + def root(self) -> Node: ... + def result(self) -> Field: ... + +class SelectionVector(_Weakrefable): + def to_array(self) -> Array: ... + +class Projector(_Weakrefable): + @property + def llvm_ir(self) -> str: ... + def evaluate( + self, batch: RecordBatch, selection: SelectionVector | None = None + ) -> list[Array]: ... + +class Filter(_Weakrefable): + @property + def llvm_ir(self) -> str: ... + def evaluate( + self, batch: RecordBatch, pool: MemoryPool, dtype: DataType | str = "int32" + ) -> SelectionVector: ... + +class TreeExprBuilder(_Weakrefable): + def make_literal( + self, value: float | str | bytes | bool, dtype: DataType | str | None + ) -> Node: ... + def make_expression( + self, root_node: Node | None, return_field: Field + ) -> Expression: ... + def make_function( + self, name: str, children: Sequence[Node | None], return_type: DataType + ) -> Node: ... + def make_field(self, field: Field | None) -> Node: ... + def make_if( + self, + condition: Node, + this_node: Node | None, + else_node: Node | None, + return_type: DataType | None, + ) -> Node: ... + def make_and(self, children: Sequence[Node | None]) -> Node: ... + def make_or(self, children: Sequence[Node | None]) -> Node: ... + def make_in_expression( + self, node: Node | None, values: Iterable[Any], dtype: DataType + ) -> Node: ... + def make_condition(self, condition: Node | None) -> Condition: ... + +class Configuration(_Weakrefable): + def __init__(self, optimize: bool = True, dump_ir: bool = False) -> None: ... + +def make_projector( + schema: Schema, + children: Sequence[Expression | None], + pool: MemoryPool | None = None, + selection_mode: Literal["NONE", "UINT16", "UINT32", "UINT64"] = "NONE", + configuration: Configuration | None = None, +) -> Projector: ... +def make_filter( + schema: Schema, + condition: Condition | None, + configuration: Configuration | None = None, +) -> Filter: ... + +class FunctionSignature(_Weakrefable): + def return_type(self) -> DataType: ... + def param_types(self) -> list[DataType]: ... + def name(self) -> str: ... + +def get_registered_function_signatures() -> list[FunctionSignature]: ... diff --git a/python/pyarrow-stubs/interchange/__init__.pyi b/python/pyarrow-stubs/interchange/__init__.pyi new file mode 100644 index 00000000000..fd5ae83c569 --- /dev/null +++ b/python/pyarrow-stubs/interchange/__init__.pyi @@ -0,0 +1,20 @@ +# 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 .from_dataframe import from_dataframe as from_dataframe + +__all__ = ["from_dataframe"] diff --git a/python/pyarrow-stubs/interchange/buffer.pyi b/python/pyarrow-stubs/interchange/buffer.pyi new file mode 100644 index 00000000000..403784bc28a --- /dev/null +++ b/python/pyarrow-stubs/interchange/buffer.pyi @@ -0,0 +1,40 @@ +# 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 enum + +from pyarrow.lib import Buffer +from typing_extensions import CapsuleType + +class DlpackDeviceType(enum.IntEnum): + CPU = 1 + CUDA = 2 + CPU_PINNED = 3 + OPENCL = 4 + VULKAN = 7 + METAL = 8 + VPI = 9 + ROCM = 10 + +class _PyArrowBuffer: + def __init__(self, x: Buffer, allow_copy: bool = True) -> None: ... + @property + def bufsize(self) -> int: ... + @property + def ptr(self) -> int: ... + def __dlpack__(self) -> CapsuleType: ... + def __dlpack_device__(self) -> tuple[DlpackDeviceType, int | None]: ... diff --git a/python/pyarrow-stubs/interchange/column.pyi b/python/pyarrow-stubs/interchange/column.pyi new file mode 100644 index 00000000000..969a66f676f --- /dev/null +++ b/python/pyarrow-stubs/interchange/column.pyi @@ -0,0 +1,84 @@ +# 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 enum + +from collections.abc import Iterable +from typing import Any, TypeAlias, TypedDict + +from pyarrow.lib import Array, ChunkedArray + +from .buffer import _PyArrowBuffer + +class DtypeKind(enum.IntEnum): + INT = 0 + UINT = 1 + FLOAT = 2 + BOOL = 20 + STRING = 21 # UTF-8 + DATETIME = 22 + CATEGORICAL = 23 + +Dtype: TypeAlias = tuple[DtypeKind, int, str, str] + +class ColumnNullType(enum.IntEnum): + NON_NULLABLE = 0 + USE_NAN = 1 + USE_SENTINEL = 2 + USE_BITMASK = 3 + USE_BYTEMASK = 4 + +class ColumnBuffers(TypedDict): + data: tuple[_PyArrowBuffer, Dtype] + validity: tuple[_PyArrowBuffer, Dtype] | None + offsets: tuple[_PyArrowBuffer, Dtype] | None + +class CategoricalDescription(TypedDict): + is_ordered: bool + is_dictionary: bool + categories: _PyArrowColumn | None + +class Endianness(enum.Enum): + LITTLE = "<" + BIG = ">" + NATIVE = "=" + NA = "|" + +class NoBufferPresent(Exception): ... + +class _PyArrowColumn: + _col: Array | ChunkedArray + + def __init__( + self, column: Array | ChunkedArray, allow_copy: bool = True + ) -> None: ... + def size(self) -> int: ... + @property + def offset(self) -> int: ... + @property + def dtype(self) -> tuple[DtypeKind, int, str, str]: ... + @property + def describe_categorical(self) -> CategoricalDescription: ... + @property + def describe_null(self) -> tuple[ColumnNullType, Any]: ... + @property + def null_count(self) -> int: ... + @property + def metadata(self) -> dict[str, Any]: ... + def num_chunks(self) -> int: ... + def get_chunks(self, n_chunks: int | None = None) -> Iterable[_PyArrowColumn]: ... + def get_buffers(self) -> ColumnBuffers: ... diff --git a/python/pyarrow-stubs/interchange/dataframe.pyi b/python/pyarrow-stubs/interchange/dataframe.pyi new file mode 100644 index 00000000000..642e3945325 --- /dev/null +++ b/python/pyarrow-stubs/interchange/dataframe.pyi @@ -0,0 +1,45 @@ +# 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, Sequence +from typing import Any, Self + +from pyarrow.interchange.column import _PyArrowColumn +from pyarrow.lib import RecordBatch, Table + +class _PyArrowDataFrame: + def __init__( + self, + df: Table | RecordBatch, + nan_as_null: bool = False, + allow_copy: bool = True, + ) -> None: ... + def __dataframe__( + self, nan_as_null: bool = False, allow_copy: bool = True + ) -> _PyArrowDataFrame: ... + @property + def metadata(self) -> dict[str, Any]: ... + def num_columns(self) -> int: ... + def num_rows(self) -> int: ... + def num_chunks(self) -> int: ... + def column_names(self) -> Iterable[str]: ... + def get_column(self, i: int) -> _PyArrowColumn: ... + def get_column_by_name(self, name: str) -> _PyArrowColumn: ... + def get_columns(self) -> Iterable[_PyArrowColumn]: ... + def select_columns(self, indices: Sequence[int]) -> Self: ... + def select_columns_by_name(self, names: Sequence[str]) -> Self: ... + def get_chunks(self, n_chunks: int | None = None) -> Iterable[Self]: ... diff --git a/python/pyarrow-stubs/interchange/from_dataframe.pyi b/python/pyarrow-stubs/interchange/from_dataframe.pyi new file mode 100644 index 00000000000..2eda94b966c --- /dev/null +++ b/python/pyarrow-stubs/interchange/from_dataframe.pyi @@ -0,0 +1,71 @@ +# 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 Any, Protocol, TypeAlias + +from pyarrow.lib import Array, Buffer, DataType, DictionaryArray, RecordBatch, Table + +from .column import ( + ColumnBuffers, + ColumnNullType, + Dtype, + DtypeKind, +) + +class DataFrameObject(Protocol): + def __dataframe__( + self, nan_as_null: bool = False, allow_copy: bool = True + ) -> Any: ... + +ColumnObject: TypeAlias = Any + +def from_dataframe(df: DataFrameObject, allow_copy: bool = True) -> Table: ... +def _from_dataframe(df: DataFrameObject, allow_copy: bool = True) -> Table: ... +def protocol_df_chunk_to_pyarrow( + df: DataFrameObject, allow_copy: bool = True +) -> RecordBatch: ... +def column_to_array(col: ColumnObject, allow_copy: bool = True) -> Array: ... +def bool_column_to_array(col: ColumnObject, allow_copy: bool = True) -> Array: ... +def categorical_column_to_dictionary( + col: ColumnObject, allow_copy: bool = True +) -> DictionaryArray: ... +def parse_datetime_format_str(format_str: str) -> tuple[str, str]: ... +def map_date_type(data_type: tuple[DtypeKind, int, str, str]) -> DataType: ... +def buffers_to_array( + buffers: ColumnBuffers, + data_type: tuple[DtypeKind, int, str, str], + length: int, + describe_null: ColumnNullType, + offset: int = 0, + allow_copy: bool = True, +) -> Array: ... +def validity_buffer_from_mask( + validity_buff: Buffer, + validity_dtype: Dtype, + describe_null: ColumnNullType, + length: int, + offset: int = 0, + allow_copy: bool = True, +) -> Buffer: ... +def validity_buffer_nan_sentinel( + data_pa_buffer: Buffer, + data_type: Dtype, + describe_null: ColumnNullType, + length: int, + offset: int = 0, + allow_copy: bool = True, +) -> Buffer: ... 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 74624bfbcd4..e0a41c8f5d8 100644 --- a/python/pyarrow-stubs/lib.pyi +++ b/python/pyarrow-stubs/lib.pyi @@ -15,19 +15,20 @@ # specific language governing permissions and limitations # under the License. -# Stub for the pyarrow.lib C extension module. Re-exports the modules that -# have been annotated so far; everything else falls back to Any via -# __getattr__ until it gets annotated in subsequent PRs. +# Stub for the pyarrow.lib C extension module. -from typing import Any, Self, final +from typing import Self, final from pyarrow.__lib.array import * # noqa: F401,F403 from pyarrow.__lib.builder import * # noqa: F401,F403 +from pyarrow.__lib.compat import * # noqa: F401,F403 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.pandas_shim import * # noqa: F401,F403 from pyarrow.__lib.scalar import * # noqa: F401,F403 from pyarrow.__lib.table import * # noqa: F401,F403 from pyarrow.__lib.tensor import * # noqa: F401,F403 @@ -41,4 +42,6 @@ class MonthDayNano(tuple[int, int, int]): def __new__(cls, sequence: tuple[int, int, int] | list[int]) -> Self: ... -def __getattr__(name: str) -> Any: ... +def cpu_count() -> int: ... +def set_cpu_count(count: int) -> None: ... +def is_opentelemetry_enabled() -> bool: ... diff --git a/python/pyarrow-stubs/orc.pyi b/python/pyarrow-stubs/orc.pyi new file mode 100644 index 00000000000..b18654c79dc --- /dev/null +++ b/python/pyarrow-stubs/orc.pyi @@ -0,0 +1,116 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from collections.abc import Sequence +from typing import IO, Any, Literal, Self + +from _typeshed import StrPath + +from . import _orc +from ._fs import _SupportedFileSystem +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: _SupportedFileSystem | str | None = 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-stubs/pandas_compat.pyi b/python/pyarrow-stubs/pandas_compat.pyi new file mode 100644 index 00000000000..e66c553e792 --- /dev/null +++ b/python/pyarrow-stubs/pandas_compat.pyi @@ -0,0 +1,76 @@ +# 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 Any, TypedDict, TypeVar + +import numpy as np +import pandas as pd + +from pandas import DatetimeTZDtype + +from .lib import Array, DataType, Schema, Table, _pandas_api as _pandas_api + +_T = TypeVar("_T") + +def get_logical_type_map() -> dict[int, str]: ... +def get_logical_type(arrow_type: DataType) -> str: ... +def get_numpy_logical_type_map() -> dict[type[np.generic], str]: ... +def get_logical_type_from_numpy(pandas_collection: Any) -> str: ... +def get_extension_dtype_info(column: Any) -> tuple[str, dict[str, Any]]: ... + +class _ColumnMetadata(TypedDict): + name: str + field_name: str + pandas_type: int + numpy_type: str + metadata: dict[str, Any] | None + +def get_column_metadata( + column: pd.Series | pd.Index, name: str, arrow_type: DataType, field_name: str +) -> _ColumnMetadata: ... +def construct_metadata( + columns_to_convert: list[pd.Series], + df: pd.DataFrame, + column_names: list[str], + index_levels: list[pd.Index], + index_descriptors: list[dict[str, Any]], + preserve_index: bool, + types: list[DataType], + column_field_names: list[str] | None = None, +) -> dict[bytes, bytes]: ... +def dataframe_to_types( + df: pd.DataFrame, preserve_index: bool | None, columns: list[str] | None = None +) -> tuple[list[str], list[DataType], dict[bytes, bytes]]: ... +def dataframe_to_arrays( + df: pd.DataFrame, + schema: Schema, + preserve_index: bool | None, + nthreads: int = 1, + columns: list[str] | None = None, + safe: bool = True, +) -> tuple[Array, Schema, int]: ... +def get_datetimetz_type(values: _T, dtype: Any, type_: Any) -> tuple[_T, DataType]: ... +def make_datetimetz(unit: str, tz: str) -> DatetimeTZDtype: ... +def table_to_dataframe( + options: Any, + table: Table, + categories: Any = None, + ignore_metadata: bool = False, + types_mapper: Any = None, +) -> pd.DataFrame: ... +def get_pandas_logical_type_map() -> dict[str, str | type[np.generic]]: ... +def make_tz_aware(series: pd.Series, tz: str) -> pd.Series: ... diff --git a/python/pyarrow-stubs/parquet/__init__.pyi b/python/pyarrow-stubs/parquet/__init__.pyi new file mode 100644 index 00000000000..5329bd6c66a --- /dev/null +++ b/python/pyarrow-stubs/parquet/__init__.pyi @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from .core import * # noqa: F401, F403 diff --git a/python/pyarrow-stubs/parquet/core.pyi b/python/pyarrow-stubs/parquet/core.pyi new file mode 100644 index 00000000000..ff9cfc1fd77 --- /dev/null +++ b/python/pyarrow-stubs/parquet/core.pyi @@ -0,0 +1,361 @@ +# 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, Iterable, Iterator, Sequence +from pathlib import Path +from typing import IO, Any, Literal, Self, TypeAlias + +from pyarrow import _parquet +from pyarrow._compute import Expression +from pyarrow._fs import FileSystem, _SupportedFileSystem +from pyarrow._parquet import ( + ColumnChunkMetaData, + ColumnSchema, + FileDecryptionProperties, + FileEncryptionProperties, + FileMetaData, + ParquetLogicalType, + ParquetReader, + ParquetSchema, + RowGroupMetaData, + SortingColumn, + Statistics, +) +from pyarrow._stubs_typing import FilterTuple, SingleOrList +from pyarrow.dataset import ParquetFileFragment, Partitioning, PartitioningFactory +from pyarrow.lib import ( + Buffer, + ChunkedArray, + DataType, + NativeFile, + RecordBatch, + Schema, + Table, +) +from typing_extensions import deprecated + +__all__ = ( + "ColumnChunkMetaData", + "ColumnSchema", + "FileDecryptionProperties", + "FileEncryptionProperties", + "FileMetaData", + "ParquetDataset", + "ParquetFile", + "ParquetLogicalType", + "ParquetReader", + "ParquetSchema", + "ParquetWriter", + "RowGroupMetaData", + "SortingColumn", + "Statistics", + "read_metadata", + "read_pandas", + "read_schema", + "read_table", + "write_metadata", + "write_table", + "write_to_dataset", + "_filters_to_expression", + "filters_to_expression", +) + +def filters_to_expression( + filters: Sequence[FilterTuple] | Sequence[Sequence[FilterTuple]], +) -> Expression: ... +@deprecated("use filters_to_expression") +def _filters_to_expression( + filters: Sequence[FilterTuple] | Sequence[Sequence[FilterTuple]], +) -> Expression: ... + +_Compression: TypeAlias = Literal[ + "gzip", "bz2", "brotli", "lz4", "zstd", "snappy", "none" +] + +class ParquetFile: + reader: ParquetReader + common_metadata: FileMetaData + + def __init__( + self, + source: str | Path | Buffer | NativeFile | IO[Any], + *, + metadata: FileMetaData | None = None, + common_metadata: FileMetaData | None = None, + read_dictionary: list[str] | None = None, + binary_type: DataType | None = None, + list_type: DataType | None = None, + memory_map: bool = False, + buffer_size: int = 0, + pre_buffer: bool = False, + coerce_int96_timestamp_unit: str | None = None, + decryption_properties: FileDecryptionProperties | None = None, + thrift_string_size_limit: int | None = None, + thrift_container_size_limit: int | None = None, + filesystem: _SupportedFileSystem | None = None, + page_checksum_verification: bool = False, + arrow_extensions_enabled: bool = True, + ) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: object, **kwargs: Any) -> None: ... + @property + def metadata(self) -> FileMetaData: ... + @property + def schema(self) -> ParquetSchema: ... + @property + def schema_arrow(self) -> Schema: ... + @property + def num_row_groups(self) -> int: ... + def close(self, force: bool = False) -> None: ... + @property + def closed(self) -> bool: ... + def read_row_group( + self, + i: int, + columns: Sequence[str | int] | None = None, + use_threads: bool = True, + use_pandas_metadata: bool = False, + ) -> Table: ... + def read_row_groups( + self, + row_groups: Sequence[int], + columns: Iterable[str | int] | None = None, + use_threads: bool = True, + use_pandas_metadata: bool = False, + ) -> Table: ... + def iter_batches( + self, + batch_size: int = 65536, + row_groups: Sequence[int] | None = None, + columns: Iterable[str | int] | None = None, + use_threads: bool = True, + use_pandas_metadata: bool = False, + ) -> Iterator[RecordBatch]: ... + def read( + self, + columns: Sequence[str | int] | None = None, + use_threads: bool = True, + use_pandas_metadata: bool = False, + ) -> Table: ... + def scan_contents( + self, columns: Iterable[str | int] | None = None, batch_size: int = 65536 + ) -> int: ... + +class ParquetWriter: + flavor: str + schema_changed: bool + schema: ParquetSchema + where: str | Path | IO[Any] + file_handler: NativeFile | None + writer: _parquet.ParquetWriter + is_open: bool + + def __init__( + self, + where: str | Path | IO[Any] | NativeFile, + schema: Schema, + filesystem: _SupportedFileSystem | None = None, + flavor: str | None = None, + version: Literal["1.0", "2.4", "2.6"] = ..., + use_dictionary: bool = True, + compression: _Compression | dict[str, _Compression] = "snappy", + write_statistics: bool | list[str] = True, + use_deprecated_int96_timestamps: bool | None = None, + compression_level: int | dict[str, int] | None = None, + use_byte_stream_split: bool | list[str] = False, + column_encoding: str | dict[str, str] | None = None, + writer_engine_version: str | None = None, + data_page_version: Literal["1.0", "2.0"] = ..., + use_compliant_nested_type: bool = True, + encryption_properties: FileEncryptionProperties | None = None, + write_batch_size: int | None = None, + dictionary_pagesize_limit: int | None = None, + store_schema: bool = True, + write_page_index: bool = False, + write_page_checksum: bool = False, + sorting_columns: Sequence[SortingColumn] | None = None, + store_decimal_as_integer: bool = False, + write_time_adjusted_to_utc: bool = False, + max_rows_per_page: int | None = None, + **options: Any, + ) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: object, **kwargs: Any) -> Literal[False]: ... + def write( + self, table_or_batch: RecordBatch | Table, row_group_size: int | None = None + ) -> None: ... + def write_batch( + self, batch: RecordBatch, row_group_size: int | None = None + ) -> None: ... + def write_table(self, table: Table, row_group_size: int | None = None) -> None: ... + def close(self) -> None: ... + def add_key_value_metadata(self, key_value_metadata: dict[str, str]) -> None: ... + +class ParquetDataset: + def __init__( + self, + path_or_paths: SingleOrList[str] + | SingleOrList[Path] + | SingleOrList[NativeFile] + | SingleOrList[IO[Any]], + filesystem: _SupportedFileSystem | None = None, + schema: Schema | None = None, + *, + filters: Expression + | FilterTuple + | Sequence[FilterTuple] + | Sequence[Sequence[FilterTuple]] + | None = None, + read_dictionary: list[str] | None = None, + binary_type: DataType | None = None, + list_type: DataType | None = None, + memory_map: bool = False, + buffer_size: int | None = None, + partitioning: str + | list[str] + | Partitioning + | PartitioningFactory + | None = "hive", + ignore_prefixes: list[str] | None = None, + pre_buffer: bool = True, + coerce_int96_timestamp_unit: str | None = None, + decryption_properties: FileDecryptionProperties | None = None, + thrift_string_size_limit: int | None = None, + thrift_container_size_limit: int | None = None, + page_checksum_verification: bool = False, + arrow_extensions_enabled: bool = True, + ) -> None: ... + def equals(self, other: ParquetDataset) -> bool: ... + @property + def schema(self) -> Schema: ... + def read( + self, + columns: list[str] | None = None, + use_threads: bool = True, + use_pandas_metadata: bool = False, + ) -> Table: ... + def read_pandas(self, **kwargs: Any) -> Table: ... + @property + def fragments(self) -> list[ParquetFileFragment]: ... + @property + def files(self) -> list[str]: ... + @property + def filesystem(self) -> FileSystem: ... + @property + def partitioning(self) -> Partitioning: ... + +def read_table( + source: SingleOrList[str] + | SingleOrList[Path] + | SingleOrList[NativeFile] + | SingleOrList[IO[Any]] + | Buffer, + *, + columns: Sequence[str] | None = None, + use_threads: bool = True, + schema: Schema | None = None, + use_pandas_metadata: bool = False, + read_dictionary: list[str] | None = None, + binary_type: DataType | None = None, + list_type: DataType | None = None, + memory_map: bool = False, + buffer_size: int = 0, + partitioning: str | list[str] | Partitioning | PartitioningFactory | None = "hive", + filesystem: _SupportedFileSystem | str | None = None, + filters: Expression + | FilterTuple + | Sequence[FilterTuple] + | Sequence[Sequence[tuple[Any, ...]]] + | None = None, + ignore_prefixes: list[str] | None = None, + pre_buffer: bool = True, + coerce_int96_timestamp_unit: str | None = None, + decryption_properties: FileDecryptionProperties | None = None, + thrift_string_size_limit: int | None = None, + thrift_container_size_limit: int | None = None, + page_checksum_verification: bool = False, + arrow_extensions_enabled: bool = True, +) -> Table: ... +def read_pandas( + source: str | Path | NativeFile | IO[Any] | Buffer, + columns: Sequence[str] | None = None, + **kwargs: Any, +) -> Table: ... +def write_table( + table: Table, + where: str | Path | NativeFile | IO[Any], + row_group_size: int | None = None, + version: Literal["1.0", "2.4", "2.6"] = "2.6", + use_dictionary: bool = True, + compression: _Compression | dict[str, _Compression] = "snappy", + write_statistics: bool | list[str] = True, + use_deprecated_int96_timestamps: bool | None = None, + coerce_timestamps: str | None = None, + allow_truncated_timestamps: bool = False, + data_page_size: int | None = None, + flavor: str | None = None, + filesystem: _SupportedFileSystem | str | None = None, + compression_level: int | dict[str, int] | None = None, + use_byte_stream_split: bool = False, + column_encoding: str | dict[str, str] | None = None, + data_page_version: Literal["1.0", "2.0"] = ..., + use_compliant_nested_type: bool = True, + encryption_properties: FileEncryptionProperties | None = None, + write_batch_size: int | None = None, + dictionary_pagesize_limit: int | None = None, + store_schema: bool = True, + write_page_index: bool = False, + write_page_checksum: bool = False, + sorting_columns: Sequence[SortingColumn] | None = None, + store_decimal_as_integer: bool = False, + write_time_adjusted_to_utc: bool = False, + max_rows_per_page: int | None = None, + **kwargs: Any, +) -> None: ... +def write_to_dataset( + table: Table | ChunkedArray, + root_path: str | Path, + partition_cols: list[str] | None = None, + filesystem: _SupportedFileSystem | None = None, + schema: Schema | None = None, + partitioning: Partitioning | list[str] | None = None, + basename_template: str | None = None, + use_threads: bool | None = None, + file_visitor: Callable[[str], None] | None = None, + existing_data_behavior: Literal["overwrite_or_ignore", "error", "delete_matching"] + | None = None, + **kwargs: Any, +) -> None: ... +def write_metadata( + schema: Schema, + where: str | NativeFile, + metadata_collector: list[FileMetaData] | None = None, + filesystem: _SupportedFileSystem | None = None, + **kwargs: Any, +) -> None: ... +def read_metadata( + where: str | Path | IO[Any] | NativeFile, + memory_map: bool = False, + decryption_properties: FileDecryptionProperties | None = None, + filesystem: _SupportedFileSystem | str | None = None, +) -> FileMetaData: ... +def read_schema( + where: str | Path | IO[Any] | NativeFile, + memory_map: bool = False, + decryption_properties: FileDecryptionProperties | None = None, + filesystem: _SupportedFileSystem | str | None = None, +) -> Schema: ... diff --git a/python/pyarrow-stubs/parquet/encryption.pyi b/python/pyarrow-stubs/parquet/encryption.pyi new file mode 100644 index 00000000000..5c185494597 --- /dev/null +++ b/python/pyarrow-stubs/parquet/encryption.pyi @@ -0,0 +1,27 @@ +# 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._parquet_encryption import ( + CryptoFactory as CryptoFactory, + DecryptionConfiguration as DecryptionConfiguration, + EncryptionConfiguration as EncryptionConfiguration, + FileSystemKeyMaterialStore as FileSystemKeyMaterialStore, + KmsClient as KmsClient, + KmsConnectionConfig as KmsConnectionConfig, + create_decryption_properties as create_decryption_properties, + create_encryption_properties as create_encryption_properties, +) diff --git a/python/pyarrow-stubs/substrait.pyi b/python/pyarrow-stubs/substrait.pyi new file mode 100644 index 00000000000..b78bbd8aebd --- /dev/null +++ b/python/pyarrow-stubs/substrait.pyi @@ -0,0 +1,38 @@ +# 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._substrait import ( + BoundExpressions, + SubstraitSchema, + deserialize_expressions, + deserialize_schema, + get_supported_functions, + run_query, + serialize_expressions, + serialize_schema, +) + +__all__ = [ + "BoundExpressions", + "get_supported_functions", + "run_query", + "deserialize_expressions", + "serialize_expressions", + "deserialize_schema", + "serialize_schema", + "SubstraitSchema", +] diff --git a/python/pyarrow-stubs/tests/util.pyi b/python/pyarrow-stubs/tests/util.pyi new file mode 100644 index 00000000000..91535fce5f4 --- /dev/null +++ b/python/pyarrow-stubs/tests/util.pyi @@ -0,0 +1,85 @@ +# 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 +from contextlib import AbstractContextManager +from decimal import Decimal +from os import PathLike +from typing import Any, ClassVar, Literal +import socket + +import pyarrow.fs + +def randsign() -> int: ... +def random_seed(seed: int) -> AbstractContextManager[None]: ... +def randdecimal(precision: int, scale: int) -> Decimal: ... +def random_ascii(length: int) -> bytes: ... +def rands(nchars: int) -> str: ... +def get_modified_env_with_pythonpath() -> dict[str, str]: ... +def invoke_script(script_name: str, *args: str) -> None: ... +def changed_environ(name: str, value: str) -> AbstractContextManager[None]: ... +def change_cwd(path: str | PathLike[str]) -> AbstractContextManager[None]: ... +def disabled_gc() -> AbstractContextManager[None]: ... +def _filesystem_uri(path: str) -> str: ... +def memory_leak_check( + f: Callable[[], Any], + metric: Literal["rss", "vms", "shared"] = "rss", + threshold: int = 131072, + iterations: int = 10, + check_interval: int = 1, +) -> None: ... + +class FSProtocolClass: + def __init__(self, path: str | PathLike[str]) -> None: ... + def __fspath__(self) -> str: ... + +class ProxyHandler(pyarrow.fs.FileSystemHandler): + __hash__: ClassVar[None] # type: ignore[assignment] + _fs: pyarrow.fs.FileSystem + def __init__(self, fs: pyarrow.fs.FileSystem) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def get_type_name(self) -> str: ... + def normalize_path(self, path: str) -> str: ... + def get_file_info(self, paths: str | list[str]) -> list[pyarrow.fs.FileInfo]: ... + def get_file_info_selector( + self, selector: pyarrow.fs.FileSelector + ) -> list[pyarrow.fs.FileInfo]: ... + def create_dir(self, path: str, recursive: bool) -> None: ... + def delete_dir(self, path: str) -> None: ... + def delete_dir_contents(self, path: str, missing_dir_ok: bool) -> None: ... + def delete_root_dir_contents(self) -> None: ... + def delete_file(self, path: str) -> None: ... + def move(self, src: str, dest: str) -> None: ... + def copy_file(self, src: str, dest: str) -> None: ... + def open_input_stream(self, path: str) -> Any: ... + def open_input_file(self, path: str) -> Any: ... + def open_output_stream(self, path: str, metadata: dict[str, str]) -> Any: ... + def open_append_stream(self, path: str, metadata: dict[str, str]) -> Any: ... + +def _ensure_minio_component_version(component: str, minimum_year: int) -> bool: ... +def _run_mc_command(mcdir: str, *args: str) -> None: ... +def windows_has_tzdata() -> bool: ... +def running_on_musllinux() -> bool: ... +def signal_wakeup_fd( + *, warn_on_full_buffer: bool = False +) -> AbstractContextManager[socket.socket]: ... +def _configure_s3_limited_user( + s3_server: dict[str, Any], policy: str, username: str, password: str +) -> None: ... +def _wait_for_minio_startup( + mcdir: str, address: str, access_key: str, secret_key: str +) -> None: ... diff --git a/python/pyarrow-stubs/util.pyi b/python/pyarrow-stubs/util.pyi new file mode 100644 index 00000000000..fb933de1c01 --- /dev/null +++ b/python/pyarrow-stubs/util.pyi @@ -0,0 +1,56 @@ +# 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 os import PathLike +from typing import Any, Protocol, TypeVar + +_F = TypeVar("_F", bound=Callable[..., Any]) +_N = TypeVar("_N") + +class _DocStringComponents(Protocol): + _docstring_components: list[str] + +def doc( + *docstrings: str | _DocStringComponents | Callable[..., Any] | None, **params: Any +) -> Callable[[_F], _F]: ... +def _is_iterable(obj: Any) -> bool: ... +def _is_path_like(path: Any) -> bool: ... +def _stringify_path(path: str | PathLike[Any]) -> str: ... +def product(seq: Sequence[_N]) -> _N: ... +def get_contiguous_span( + shape: tuple[int, ...], strides: tuple[int, ...], itemsize: int +) -> tuple[int, int]: ... +def find_free_port() -> int: ... +def guid() -> str: ... +def _download_urllib(url: str, out_path: str | PathLike[Any]) -> None: ... +def _download_requests(url: str, out_path: str | PathLike[Any]) -> None: ... +def download_tzdata_on_windows() -> None: ... +def _deprecate_api( + old_name: str, + new_name: str, + api: Any, + next_version: str, + type: type[Warning] = ..., +) -> Any: ... +def _deprecate_class( + old_name: str, + new_class: type[Any], + next_version: str, + instancecheck: bool = True, +) -> type[Any]: ... +def _break_traceback_cycle_from_frame(frame: Any) -> 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 b404c261f32..79a15067067 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -120,15 +120,9 @@ files = ["pyarrow-stubs", "pyarrow-stubs-tests"] # usage is rejected, so an ignore that is no longer needed is an error there. 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.*"] -follow_imports = "skip" - # Optional dependencies without type hints. [[tool.mypy.overrides]] -module = ["fsspec", "sparse"] +module = ["cuda", "fsspec", "numba.*", "sparse"] ignore_missing_imports = true [tool.pyright] @@ -151,12 +145,10 @@ executionEnvironments = [ reportMissingModuleSource = false [tool.ty.analysis] -# Modules that will be annotated in later PRs (GH-32609), and the optional -# sparse dependency, which has no type hints. Treat them as Any. +# Optional dependencies without type hints. Treat them as Any. replace-imports-with-any = [ - "pyarrow._compute", - "pyarrow.compute", - "pyarrow.interchange.**", + "cuda", + "numba.**", "sparse", ] @@ -166,9 +158,17 @@ 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"] +include = [ + "pyarrow-stubs/__lib/array.pyi", + "pyarrow-stubs/__lib/scalar.pyi", + "pyarrow-stubs/_compute.pyi", + "pyarrow-stubs/_flight.pyi", + "pyarrow-stubs/_hdfs.pyi", +] [tool.ty.overrides.rules] -# Some array classes override methods with a different signature at runtime. +# Some array and scalar classes override methods with a different signature at +# runtime, and Expression.__eq__ and __ne__ return an Expression rather than a +# bool. incompatible-method-override = "ignore" [[tool.ty.overrides]] diff --git a/python/scripts/run_stubtest.py b/python/scripts/run_stubtest.py index e89e2a6e6db..a2b853d6750 100644 --- a/python/scripts/run_stubtest.py +++ b/python/scripts/run_stubtest.py @@ -59,12 +59,22 @@ def main(argv): # and stubtest would check them as if they were stubs. with tempfile.TemporaryDirectory() as tmpdir, contextlib.chdir(tmpdir): os.symlink(STUBS_DIR, Path(tmpdir) / "pyarrow") + allowlists = ["--allowlist", str(ALLOWLIST)] + if sys.version_info < (3, 12): + # Classes that support the buffer protocol only have a __buffer__ + # method from Python 3.12 on (PEP 688), while the stubs declare it + # for every version, like typeshed does. Unused entries fail + # stubtest, so this can't be in the allowlist file. + version_allowlist = Path(tmpdir) / "allowlist.txt" + version_allowlist.write_text( + r"pyarrow\.__lib\.[a-z]+\.[A-Za-z0-9_]+\.__buffer__" "\n") + allowlists += ["--allowlist", str(version_allowlist)] options = stubtest.parse_options([ "pyarrow", "--ignore-missing-stub", # Every Cython extension type is a disjoint base (PEP 800). "--ignore-disjoint-bases", - "--allowlist", str(ALLOWLIST), + *allowlists, "--mypy-config-file", str(PYTHON_DIR / "pyproject.toml"), *argv, ])