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/__init__.pyi b/python/pyarrow-stubs/__init__.pyi index 5f34a72a63a..9421708baf8 100644 --- a/python/pyarrow-stubs/__init__.pyi +++ b/python/pyarrow-stubs/__init__.pyi @@ -43,8 +43,17 @@ from pyarrow.lib import ( Bool8Type as Bool8Type, BooleanArray as BooleanArray, BooleanScalar as BooleanScalar, + Buffer as Buffer, + BufferOutputStream as BufferOutputStream, + BufferReader as BufferReader, + BufferedInputStream as BufferedInputStream, + BufferedOutputStream as BufferedOutputStream, BuildInfo as BuildInfo, + CacheOptions as CacheOptions, ChunkedArray as ChunkedArray, + Codec as Codec, + CompressedInputStream as CompressedInputStream, + CompressedOutputStream as CompressedOutputStream, CppBuildInfo as CppBuildInfo, DataType as DataType, Date32Array as Date32Array, @@ -88,6 +97,7 @@ from pyarrow.lib import ( FixedSizeBinaryArray as FixedSizeBinaryArray, FixedSizeBinaryScalar as FixedSizeBinaryScalar, FixedSizeBinaryType as FixedSizeBinaryType, + FixedSizeBufferWriter as FixedSizeBufferWriter, FixedSizeListArray as FixedSizeListArray, FixedSizeListScalar as FixedSizeListScalar, FixedSizeListType as FixedSizeListType, @@ -130,7 +140,9 @@ from pyarrow.lib import ( MapScalar as MapScalar, MapType as MapType, MemoryManager as MemoryManager, + MemoryMappedFile as MemoryMappedFile, MemoryPool as MemoryPool, + MockOutputStream as MockOutputStream, Month as Month, MonthDayNano as MonthDayNano, MonthDayNanoIntervalArray as MonthDayNanoIntervalArray, @@ -138,14 +150,19 @@ from pyarrow.lib import ( MonthIntervalArray as MonthIntervalArray, MonthIntervalScalar as MonthIntervalScalar, NA as NA, + NativeFile as NativeFile, NullArray as NullArray, NullScalar as NullScalar, NumericArray as NumericArray, + OSFile as OSFile, OpaqueArray as OpaqueArray, OpaqueScalar as OpaqueScalar, OpaqueType as OpaqueType, ProxyMemoryPool as ProxyMemoryPool, + PythonFile as PythonFile, RecordBatch as RecordBatch, + RecordBatchReader as RecordBatchReader, + ResizableBuffer as ResizableBuffer, RunEndEncodedArray as RunEndEncodedArray, RunEndEncodedScalar as RunEndEncodedScalar, RunEndEncodedType as RunEndEncodedType, @@ -176,6 +193,7 @@ from pyarrow.lib import ( TimestampArray as TimestampArray, TimestampScalar as TimestampScalar, TimestampType as TimestampType, + TransformInputStream as TransformInputStream, UInt16Array as UInt16Array, UInt16Scalar as UInt16Scalar, UInt32Array as UInt32Array, @@ -192,6 +210,7 @@ from pyarrow.lib import ( UuidScalar as UuidScalar, UuidType as UuidType, VersionInfo as VersionInfo, + allocate_buffer as allocate_buffer, array as array, binary as binary, binary_view as binary_view, @@ -199,12 +218,14 @@ from pyarrow.lib import ( bool_ as bool_, build_info as build_info, chunked_array as chunked_array, + compress as compress, concat_arrays as concat_arrays, concat_batches as concat_batches, concat_tables as concat_tables, cpp_build_info as cpp_build_info, cpp_version as cpp_version, cpp_version_info as cpp_version_info, + create_memory_map as create_memory_map, date32 as date32, date64 as date64, day_time_interval as day_time_interval, @@ -212,6 +233,7 @@ from pyarrow.lib import ( decimal256 as decimal256, decimal32 as decimal32, decimal64 as decimal64, + decompress as decompress, default_cpu_memory_manager as default_cpu_memory_manager, default_memory_pool as default_memory_pool, dense_union as dense_union, @@ -223,12 +245,15 @@ from pyarrow.lib import ( float16 as float16, float32 as float32, float64 as float64, + foreign_buffer as foreign_buffer, from_numpy_dtype as from_numpy_dtype, infer_type as infer_type, + input_stream as input_stream, int16 as int16, int32 as int32, int64 as int64, int8 as int8, + io_thread_count as io_thread_count, jemalloc_memory_pool as jemalloc_memory_pool, jemalloc_set_decay_ms as jemalloc_set_decay_ms, json_ as json_, @@ -242,13 +267,16 @@ from pyarrow.lib import ( log_memory_allocations as log_memory_allocations, logging_memory_pool as logging_memory_pool, map_ as map_, + memory_map as memory_map, mimalloc_memory_pool as mimalloc_memory_pool, month_day_nano_interval as month_day_nano_interval, month_interval as month_interval, null as null, nulls as nulls, opaque as opaque, + output_stream as output_stream, proxy_memory_pool as proxy_memory_pool, + py_buffer as py_buffer, record_batch as record_batch, register_extension_type as register_extension_type, repeat as repeat, @@ -256,6 +284,7 @@ from pyarrow.lib import ( runtime_info as runtime_info, scalar as scalar, schema as schema, + set_io_thread_count as set_io_thread_count, set_memory_pool as set_memory_pool, set_timezone_db_path as set_timezone_db_path, sparse_union as sparse_union, @@ -269,6 +298,7 @@ from pyarrow.lib import ( time64 as time64, timestamp as timestamp, total_allocated_bytes as total_allocated_bytes, + transcoding_input_stream as transcoding_input_stream, type_for_alias as type_for_alias, uint16 as uint16, uint32 as uint32, @@ -281,7 +311,19 @@ from pyarrow.lib import ( uuid as uuid, ) +from pyarrow import ipc as ipc from pyarrow import types as types +from pyarrow.ipc import ( + Message as Message, + MessageReader as MessageReader, + MetadataVersion as MetadataVersion, + RecordBatchFileReader as RecordBatchFileReader, + RecordBatchFileWriter as RecordBatchFileWriter, + RecordBatchStreamReader as RecordBatchStreamReader, + RecordBatchStreamWriter as RecordBatchStreamWriter, + deserialize_pandas as deserialize_pandas, + serialize_pandas as serialize_pandas, +) # pyarrow/__init__.py imports pyarrow.lib._NULL as NULL NULL: NullScalar diff --git a/python/pyarrow-stubs/__lib/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/_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/_csv.pyi b/python/pyarrow-stubs/_csv.pyi new file mode 100644 index 00000000000..a6f29338634 --- /dev/null +++ b/python/pyarrow-stubs/_csv.pyi @@ -0,0 +1,170 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from collections.abc import Callable, Sequence +from typing import IO, Any, Literal, NamedTuple + +from _typeshed import StrPath + +from . import lib + +class ReadOptions(lib._Weakrefable): + use_threads: bool + block_size: int | None + skip_rows: int + skip_rows_after_names: int + column_names: Sequence[str] | None + autogenerate_column_names: bool + encoding: str + + def __init__( + self, + use_threads: bool | None = None, + *, + block_size: int | None = None, + skip_rows: int | None = None, + skip_rows_after_names: int | None = None, + column_names: Sequence[str] | None = None, + autogenerate_column_names: bool | None = None, + encoding: str = "utf8", + ) -> None: ... + def equals(self, other: ReadOptions) -> bool: ... + def validate(self) -> None: ... + +class ParseOptions(lib._Weakrefable): + delimiter: str + quote_char: str | Literal[False] + double_quote: bool + escape_char: str | Literal[False] + newlines_in_values: bool + ignore_empty_lines: bool + invalid_row_handler: Callable[[InvalidRow], str] | None + + def __init__( + self, + delimiter: str | None = None, + *, + quote_char: str | Literal[False] | None = None, + double_quote: bool | None = None, + escape_char: str | Literal[False] | None = None, + newlines_in_values: bool | None = None, + ignore_empty_lines: bool | None = None, + invalid_row_handler: Callable[[InvalidRow], str] | None = None, + ) -> None: ... + def equals(self, other: ParseOptions) -> bool: ... + def validate(self) -> None: ... + +class ConvertOptions(lib._Weakrefable): + check_utf8: bool + column_types: ( + lib.Schema | dict[str, lib.DataType] | Sequence[tuple[str, lib.DataType]] | None + ) + null_values: list[str] | None + true_values: list[str] | None + false_values: list[str] | None + decimal_point: str + strings_can_be_null: bool + quoted_strings_can_be_null: bool + include_columns: list[str] | None + include_missing_columns: bool + auto_dict_encode: bool + auto_dict_max_cardinality: int | None + timestamp_parsers: Sequence[str | lib._Weakrefable] | None + + def __init__( + self, + check_utf8: bool | None = None, + *, + column_types: ( + lib.Schema + | dict[str, lib.DataType] + | Sequence[tuple[str, lib.DataType]] + | None + ) = None, + null_values: Sequence[str] | None = None, + true_values: Sequence[str] | None = None, + false_values: Sequence[str] | None = None, + decimal_point: str | None = None, + strings_can_be_null: bool | None = None, + quoted_strings_can_be_null: bool | None = None, + include_columns: Sequence[str] | None = None, + include_missing_columns: bool | None = None, + auto_dict_encode: bool | None = None, + auto_dict_max_cardinality: int | None = None, + timestamp_parsers: Sequence[str | lib._Weakrefable] | None = None, + ) -> None: ... + def equals(self, other: ConvertOptions) -> bool: ... + def validate(self) -> None: ... + +class WriteOptions(lib._Weakrefable): + include_header: bool + batch_size: int + delimiter: str + quoting_style: Literal["needed", "all_valid", "none"] + quoting_header: Literal["needed", "all_valid", "none"] + + def __init__( + self, + include_header: bool = True, + *, + batch_size: int = 1024, + delimiter: str = ",", + quoting_style: Literal["needed", "all_valid", "none"] = "needed", + quoting_header: Literal["needed", "all_valid", "none"] = "needed", + ) -> None: ... + def validate(self) -> None: ... + +class InvalidRow(NamedTuple): + expected_columns: int + actual_columns: int + number: int | None + text: str + +class CSVWriter(lib._CRecordBatchWriter): + def __init__( + self, + sink: StrPath | lib.NativeFile | IO[Any], + schema: lib.Schema, + write_options: WriteOptions | None = None, + *, + memory_pool: lib.MemoryPool | None = None, + ) -> None: ... + +class CSVStreamingReader(lib.RecordBatchReader): ... + +ISO8601: lib._Weakrefable + +def open_csv( + input_file: StrPath | lib.NativeFile | IO[Any], + read_options: ReadOptions | None = None, + parse_options: ParseOptions | None = None, + convert_options: ConvertOptions | None = None, + memory_pool: lib.MemoryPool | None = None, +) -> CSVStreamingReader: ... +def read_csv( + input_file: StrPath | lib.NativeFile | IO[Any], + read_options: ReadOptions | None = None, + parse_options: ParseOptions | None = None, + convert_options: ConvertOptions | None = None, + memory_pool: lib.MemoryPool | None = None, +) -> lib.Table: ... +def write_csv( + data: lib.RecordBatch | lib.Table, + output_file: StrPath | lib.NativeFile | IO[Any], + write_options: WriteOptions | None = None, + memory_pool: lib.MemoryPool | None = None, +) -> None: ... diff --git a/python/pyarrow-stubs/_feather.pyi b/python/pyarrow-stubs/_feather.pyi new file mode 100644 index 00000000000..ebc922ae084 --- /dev/null +++ b/python/pyarrow-stubs/_feather.pyi @@ -0,0 +1,47 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from collections.abc import Sequence +from typing import IO, Any, Literal, Self + +from _typeshed import StrPath + +from .lib import Buffer, NativeFile, Table, _Weakrefable + +class FeatherError(Exception): ... + +def write_feather( + table: Table, + dest: StrPath | IO[Any] | NativeFile, + compression: str | None = None, + compression_level: int | None = None, + chunksize: int | None = None, + version: Literal[1, 2] = 2, +) -> None: ... + +class FeatherReader(_Weakrefable): + def __new__( + cls, + source: StrPath | IO[Any] | NativeFile | Buffer, + use_memory_map: bool = True, + use_threads: bool = True, + ) -> Self: ... + @property + def version(self) -> str: ... + def read(self) -> Table: ... + def read_indices(self, indices: Sequence[int]) -> Table: ... + def read_names(self, names: Sequence[str]) -> Table: ... diff --git a/python/pyarrow-stubs/_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/_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 90a79999511..aa65de8af99 100644 --- a/python/pyarrow-stubs/_stubs_typing.pyi +++ b/python/pyarrow-stubs/_stubs_typing.pyi @@ -24,6 +24,9 @@ from pyarrow.lib import Array, ChunkedArray from pyarrow import lib +Compression: TypeAlias = Literal[ + "gzip", "bz2", "brotli", "lz4", "lz4_frame", "lz4_raw", "zstd", "snappy" +] Order: TypeAlias = Literal["ascending", "descending"] MapsAsPydicts: TypeAlias = Literal["lossy", "strict"] NullEncoding: TypeAlias = Literal["mask", "encode"] @@ -36,6 +39,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/csv.pyi b/python/pyarrow-stubs/csv.pyi new file mode 100644 index 00000000000..2061f96e530 --- /dev/null +++ b/python/pyarrow-stubs/csv.pyi @@ -0,0 +1,30 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from pyarrow._csv import ( + ISO8601 as ISO8601, + ConvertOptions as ConvertOptions, + CSVStreamingReader as CSVStreamingReader, + CSVWriter as CSVWriter, + InvalidRow as InvalidRow, + ParseOptions as ParseOptions, + ReadOptions as ReadOptions, + WriteOptions as WriteOptions, + open_csv as open_csv, + read_csv as read_csv, + write_csv as write_csv, +) diff --git a/python/pyarrow-stubs/feather.pyi b/python/pyarrow-stubs/feather.pyi new file mode 100644 index 00000000000..287871edbe2 --- /dev/null +++ b/python/pyarrow-stubs/feather.pyi @@ -0,0 +1,62 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from collections.abc import Iterable +from typing import IO, Any, Literal + +import pandas as pd +from _typeshed import StrPath +from pyarrow import lib +from pyarrow.lib import Table + +from ._feather import FeatherError as FeatherError + +class FeatherDataset: + path_or_paths: str | list[str] + validate_schema: bool + + def __init__( + self, path_or_paths: str | list[str], validate_schema: bool = True + ) -> None: ... + def read_table(self, columns: list[str] | None = None) -> Table: ... + def validate_schemas(self, piece: Any, table: Table) -> None: ... + def read_pandas( + self, columns: list[str] | None = None, use_threads: bool = True + ) -> pd.DataFrame: ... + +def check_chunked_overflow(name: str, col: Any) -> None: ... +def write_feather( + df: pd.DataFrame | Table | lib.ChunkedArray, + dest: StrPath | IO[Any] | lib.NativeFile, + compression: Literal["zstd", "lz4", "uncompressed", "snappy"] | None = None, + compression_level: int | None = None, + chunksize: int | None = None, + version: Literal[1, 2] = 2, +) -> None: ... +def read_feather( + source: StrPath | IO[Any] | lib.NativeFile, + columns: list[str] | None = None, + use_threads: bool = True, + memory_map: bool = False, + **kwargs: Any, +) -> pd.DataFrame: ... +def read_table( + source: StrPath | IO[Any] | lib.NativeFile, + columns: Iterable[str | int] | None = None, + memory_map: bool = False, + use_threads: bool = True, +) -> Table: ... diff --git a/python/pyarrow-stubs/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/ipc.pyi b/python/pyarrow-stubs/ipc.pyi new file mode 100644 index 00000000000..b1daedb27db --- /dev/null +++ b/python/pyarrow-stubs/ipc.pyi @@ -0,0 +1,113 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from io import IOBase + +from _typeshed import StrPath +import pandas as pd +import pyarrow.lib as lib + +from pyarrow.lib import ( + Alignment as Alignment, + IpcReadOptions as IpcReadOptions, + IpcWriteOptions as IpcWriteOptions, + Message as Message, + MessageReader as MessageReader, + MetadataVersion as MetadataVersion, + ReadStats as ReadStats, + RecordBatchReader as RecordBatchReader, + WriteStats as WriteStats, + _ReadPandasMixin as _ReadPandasMixin, + get_record_batch_size as get_record_batch_size, + get_tensor_size as get_tensor_size, + read_message as read_message, + read_record_batch as read_record_batch, + read_schema as read_schema, + read_tensor as read_tensor, + write_tensor as write_tensor, +) + +class RecordBatchStreamReader(lib._RecordBatchStreamReader): + def __init__( + self, + source: bytes | lib.Buffer | lib.NativeFile | IOBase, + *, + options: IpcReadOptions | None = None, + memory_pool: lib.MemoryPool | None = None, + ) -> None: ... + +class RecordBatchStreamWriter(lib._RecordBatchStreamWriter): + def __init__( + self, + sink: str | lib.NativeFile | IOBase, + schema: lib.Schema, + *, + options: IpcWriteOptions | None = None, + ) -> None: ... + +class RecordBatchFileReader(lib._RecordBatchFileReader): + def __init__( + self, + source: bytes | lib.Buffer | lib.NativeFile | IOBase, + footer_offset: int | None = None, + *, + options: IpcReadOptions | None = None, + memory_pool: lib.MemoryPool | None = None, + ) -> None: ... + +class RecordBatchFileWriter(lib._RecordBatchFileWriter): + def __init__( + self, + sink: str | lib.NativeFile | IOBase, + schema: lib.Schema, + *, + options: IpcWriteOptions | None = None, + metadata: lib.KeyValueMetadata | dict[bytes, bytes] | None = None, + ) -> None: ... + +def new_stream( + sink: str | lib.NativeFile | IOBase, + schema: lib.Schema, + *, + options: IpcWriteOptions | None = None, +) -> RecordBatchStreamWriter: ... +def open_stream( + source: bytes | int | lib.Buffer | lib.NativeFile | IOBase, + *, + options: IpcReadOptions | None = None, + memory_pool: lib.MemoryPool | None = None, +) -> RecordBatchStreamReader: ... +def new_file( + sink: str | lib.NativeFile | IOBase, + schema: lib.Schema, + *, + options: IpcWriteOptions | None = None, + metadata: lib.KeyValueMetadata | dict[bytes, bytes] | None = None, +) -> RecordBatchFileWriter: ... +def open_file( + source: StrPath | bytes | lib.Buffer | lib.NativeFile | IOBase, + footer_offset: int | None = None, + *, + options: IpcReadOptions | None = None, + memory_pool: lib.MemoryPool | None = None, +) -> RecordBatchFileReader: ... +def serialize_pandas( + df: pd.DataFrame, *, nthreads: int | None = None, preserve_index: bool | None = None +) -> lib.Buffer: ... +def deserialize_pandas( + buf: lib.Buffer, *, use_threads: bool = True +) -> pd.DataFrame: ... diff --git a/python/pyarrow-stubs/json.pyi b/python/pyarrow-stubs/json.pyi new file mode 100644 index 00000000000..d67cf434b23 --- /dev/null +++ b/python/pyarrow-stubs/json.pyi @@ -0,0 +1,23 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from pyarrow._json import ( + ParseOptions as ParseOptions, + ReadOptions as ReadOptions, + open_json as open_json, + read_json as read_json, +) diff --git a/python/pyarrow-stubs/lib.pyi b/python/pyarrow-stubs/lib.pyi index 818241e224e..01fb54cbb34 100644 --- a/python/pyarrow-stubs/lib.pyi +++ b/python/pyarrow-stubs/lib.pyi @@ -27,6 +27,7 @@ from pyarrow.__lib.config import * # noqa: F401,F403 from pyarrow.__lib.device import * # noqa: F401,F403 from pyarrow.__lib.error import * # noqa: F401,F403 from pyarrow.__lib.io import * # noqa: F401,F403 +from pyarrow.__lib.ipc import * # noqa: F401,F403 from pyarrow.__lib.memory import * # noqa: F401,F403 from pyarrow.__lib.scalar import * # noqa: F401,F403 from pyarrow.__lib.table import * # noqa: F401,F403 diff --git a/python/pyarrow-stubs/orc.pyi b/python/pyarrow-stubs/orc.pyi new file mode 100644 index 00000000000..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/pyproject.toml b/python/pyproject.toml index 1556354f6bd..3a6288d1252 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -166,7 +166,11 @@ include = ["pyarrow-stubs", "pyarrow-stubs-tests"] # ty doesn't honor `# type: ignore[]` comments, so disable the # rules that those comments suppress for mypy. [[tool.ty.overrides]] -include = ["pyarrow-stubs/__lib/array.pyi", "pyarrow-stubs/__lib/scalar.pyi"] +include = [ + "pyarrow-stubs/__lib/array.pyi", + "pyarrow-stubs/__lib/scalar.pyi", + "pyarrow-stubs/_hdfs.pyi", +] [tool.ty.overrides.rules] # Some array and scalar classes override methods with a different signature at # runtime.