This is an automated email from the ASF dual-hosted git repository.
paleolimbot pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-nanoarrow.git
The following commit(s) were added to refs/heads/main by this push:
new 81310672 feat(python): check Cython stubs against compiled extensions
(#1026)
81310672 is described below
commit 813106724d580623545aef8c1698758b0fba5f76
Author: Muhammad Umar Nadeem <[email protected]>
AuthorDate: Sat Nov 21 18:58:15 2026 -0800
feat(python): check Cython stubs against compiled extensions (#1026)
Fixes #624.
The workflow looked for `.pyx` files in the C source tree, so the
stub-check loop never ran. The Python suite now compares public
declarations in each checked-in stub with the compiled extension. It
caught two missing methods, `CArrayBuilder.ensure_buffers` and
`CSchemaBuilder.set_map_keys_sorted`.
The regeneration script stages its output before updating the checked-in
files, so a missing generated stub leaves the existing files intact.
Validation on Python 3.13: both omissions reproduced before the stub
updates, 297 tests passed (4 skipped), and 118 doctests passed.
Regenerated all eight stubs in a scratch tree and verified they passed
the new check.
AI assistance: Codex prepared the check and stub updates and ran the
local validation.
---
.github/workflows/python.yaml | 26 ++--
python/README.md | 14 ++
python/generate_type_stubs.py | 118 ++++++++++++++++
python/generate_type_stubs.sh | 47 ++++---
.../_utils.pyi => requirements-stubs.txt} | 25 +---
python/src/nanoarrow/_array.pyi | 97 ++++++++-----
python/src/nanoarrow/_array.pyx | 2 +-
python/src/nanoarrow/_array_stream.pyi | 63 +++++----
python/src/nanoarrow/_buffer.pyi | 95 ++++++++-----
python/src/nanoarrow/_device.pyi | 67 ++++-----
python/src/nanoarrow/_ipc_lib.pyi | 34 ++---
python/src/nanoarrow/_schema.pyi | 143 +++++++++++++------
python/src/nanoarrow/_schema.pyx | 2 +-
python/src/nanoarrow/_types.pyi | 154 ++++++++++-----------
python/src/nanoarrow/_utils.pyi | 79 +++++++++--
python/tests/test_type_stubs.py | 67 +++++++++
16 files changed, 709 insertions(+), 324 deletions(-)
diff --git a/.github/workflows/python.yaml b/.github/workflows/python.yaml
index 22c8cc36..7038a5d6 100644
--- a/.github/workflows/python.yaml
+++ b/.github/workflows/python.yaml
@@ -59,7 +59,12 @@ jobs:
- name: Install nanoarrow
run: |
pushd python
- pip install .[test]
+ if [[ "${{ matrix.python-version }}" == "3.13" ]]; then
+ pip install -r requirements-stubs.txt 'meson>=1.3.0' meson-python
+ pip install --no-build-isolation '.[test]'
+ else
+ pip install '.[test]'
+ fi
popd
pip list
@@ -67,15 +72,18 @@ jobs:
run: |
pytest python/tests -v -s
- - name: Check type stubs
- if: success() && matrix.python-version == '3.13'
+ - name: Check generated type stubs
+ if: matrix.python-version == '3.13'
run: |
- pip install mypy
- cd src/nanoarrow
- for mod in $(find . -name "*.pyx" | sed -e "s|./||" -e "s|.pyx||");
do
- cat $mod
- stubtest "nanoarrow.$mod"
- done
+ bash python/generate_type_stubs.sh
+ stubs='python/src/nanoarrow/*.pyi'
+ changes=$(git status --porcelain -- "$stubs")
+ if [[ -n "$changes" ]]; then
+ git diff -- "$stubs"
+ printf '%s\n' "$changes"
+ exit 1
+ fi
+ mypy --follow-imports=silent python/src/nanoarrow/*.pyi
- name: Run doctests
if: success() && matrix.python-version == '3.13'
diff --git a/python/README.md b/python/README.md
index bb937654..f16fa1ac 100644
--- a/python/README.md
+++ b/python/README.md
@@ -437,4 +437,18 @@ pip install -e ".[test]"
pytest -vvx
```
+CI regenerates the Cython stubs on Python 3.13 and checks that the generated
+files match the checked-in stubs. The generator includes signatures and
+annotations exposed by the compiled extensions. To regenerate locally, run
+these commands with Python 3.13 from the `python` directory:
+
+```shell
+pip install -r requirements-stubs.txt 'meson>=1.3.0' meson-python
+pip install --no-build-isolation .
+bash generate_type_stubs.sh
+```
+
+The script replaces the generated files after generation and formatting
+succeed. Review the diff before committing it.
+
CMake is currently required to ensure that the vendored copy of nanoarrow in
the Python package stays in sync with the nanoarrow sources in the working tree.
diff --git a/python/generate_type_stubs.py b/python/generate_type_stubs.py
new file mode 100644
index 00000000..67645d3a
--- /dev/null
+++ b/python/generate_type_stubs.py
@@ -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.
+
+import inspect
+import sys
+from enum import Enum, IntEnum
+from pathlib import Path
+
+from mypy.stubdoc import ArgSig, FunctionSig
+from mypy.stubgenc import InspectionStubGenerator
+from mypy.util import quote_docstring
+
+
+def _is_cython_function(value):
+ return type(value).__name__ == "cython_function_or_method"
+
+
+def _annotation(value):
+ return None if value is inspect.Signature.empty else
inspect.formatannotation(value)
+
+
+class CythonStubGenerator(InspectionStubGenerator):
+ """Use Python signature metadata for Cython functions exposed by
stubgen."""
+
+ def is_skipped_attribute(self, name):
+ # These implementation details can reference the Cython build version.
+ return name in {
+ "__pyx_capi__",
+ "__pyx_vtable__",
+ "__reduce_cython__",
+ "__setstate_cython__",
+ "__test__",
+ } or super().is_skipped_attribute(name)
+
+ def is_function(self, value):
+ return _is_cython_function(value) or super().is_function(value)
+
+ def generate_class_stub(self, class_name, cls, output, parent_class=None):
+ if not issubclass(cls, Enum):
+ return super().generate_class_stub(class_name, cls, output,
parent_class)
+
+ # Enum members are assignments in stubs, and Cython can add private
bases.
+ self.record_name(class_name)
+ base = self.add_name(
+ "enum.IntEnum" if issubclass(cls, IntEnum) else "enum.Enum"
+ )
+ output.append(f"{self._indent}class {class_name}({base}):")
+ if cls.__doc__:
+ doc = quote_docstring(self._indent_docstring(cls.__doc__))
+ output.append(f"{self._indent} {doc}")
+ output.extend(
+ f"{self._indent} {name} = {member.value!r}"
+ for name, member in cls.__members__.items()
+ )
+
+ def get_default_function_sig(self, func, ctx):
+ if not _is_cython_function(func):
+ return super().get_default_function_sig(func, ctx)
+ try:
+ sig = inspect.signature(func)
+ except (TypeError, ValueError):
+ return super().get_default_function_sig(func, ctx)
+
+ args = []
+ previous = None
+ for param in sig.parameters.values():
+ kind = param.kind
+ if previous is param.POSITIONAL_ONLY and kind is not previous:
+ args.append(ArgSig("/"))
+ if kind is param.KEYWORD_ONLY and previous not in (
+ param.KEYWORD_ONLY,
+ param.VAR_POSITIONAL,
+ ):
+ args.append(ArgSig("*"))
+
+ prefix = {param.VAR_POSITIONAL: "*", param.VAR_KEYWORD:
"**"}.get(kind, "")
+ args.append(
+ ArgSig(
+ prefix + param.name,
+ _annotation(param.annotation),
+ default=param.default is not param.empty,
+ )
+ )
+ previous = kind
+
+ if previous is inspect.Parameter.POSITIONAL_ONLY:
+ args.append(ArgSig("/"))
+ return FunctionSig(ctx.name, args, _annotation(sig.return_annotation))
+
+
+def main(output_dir, modules):
+ for module in modules:
+ generator = CythonStubGenerator(module, modules,
include_docstrings=True)
+ # C imports are not visible to stubgen's Python import inspection.
+ if module == "nanoarrow._array_stream":
+ generator.known_imports["nanoarrow._array"] = ["CArray"]
+ generator.known_imports["nanoarrow._schema"] = ["CSchema"]
+ generator.generate_module()
+ path = output_dir / f"{module.rsplit('.', 1)[1]}.pyi"
+ path.write_text(generator.output(), encoding="utf-8")
+
+
+if __name__ == "__main__":
+ main(Path(sys.argv[1]), sys.argv[2:])
diff --git a/python/generate_type_stubs.sh b/python/generate_type_stubs.sh
index e250f54a..6663e1dc 100755
--- a/python/generate_type_stubs.sh
+++ b/python/generate_type_stubs.sh
@@ -15,13 +15,17 @@
# specific language governing permissions and limitations
# under the License.
-SOURCE_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
+set -euo pipefail
+
+# Generates src/nanoarrow/*.pyi given the currently installed copy of
+# nanoarrow. See requirements-stubs.txt for the regeneration environment.
-# Generates src/nanoarrow/*.pxi given the currently installed copy of
-# nanoarrow. Requires mypy and black (where black is pinned to the
-# same version as in pre-commit)
+SOURCE_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
+GENERATED_DIR="$(mktemp -d)"
+trap 'rm -rf "$GENERATED_DIR"' EXIT
-pushd "${SOURCE_DIR}"
+cd "${SOURCE_DIR}/src/nanoarrow"
+shopt -s nullglob
# We'll add the license to the start of the files
LICENSE='
@@ -43,17 +47,28 @@ LICENSE='
# under the License.
'
-# Remove old stubs
-find src/nanoarrow -name "*.pyi" -delete
+modules=()
+sources=(*.pyx)
+if (( ${#sources[@]} == 0 )); then
+ echo "No Cython sources found" >&2
+ exit 1
+fi
+for source in "${sources[@]}"; do
+ modules+=("nanoarrow.${source%.pyx}")
+done
+mkdir "$GENERATED_DIR/raw"
+python "$SOURCE_DIR/generate_type_stubs.py" "$GENERATED_DIR/raw"
"${modules[@]}"
-# Generate new ones
-pushd src/nanoarrow
-for mod in $(find . -name "*.pyx" | sed -e "s|./||" -e "s|.pyx||"); do
- stubgen --module "nanoarrow.${mod}" --include-docstrings -o ../../build/tmp
- echo "$LICENSE" > "${mod}.pyi"
- cat "../../build/tmp/nanoarrow/${mod}.pyi" >> "${mod}.pyi"
- black "${mod}.pyi"
+# Only replace the source stubs after generation and formatting succeed.
+for source in "${sources[@]}"; do
+ stub="${source%.pyx}.pyi"
+ {
+ printf '%s\n' "$LICENSE"
+ cat "$GENERATED_DIR/raw/$stub"
+ } > "$GENERATED_DIR/$stub"
done
-popd
+black "$GENERATED_DIR"/*.pyi
-popd
+# All .pyi files in this directory are generated. Remove stubs for deleted
modules.
+rm -f -- ./*.pyi
+cp "$GENERATED_DIR"/*.pyi .
diff --git a/python/src/nanoarrow/_utils.pyi b/python/requirements-stubs.txt
similarity index 50%
copy from python/src/nanoarrow/_utils.pyi
copy to python/requirements-stubs.txt
index 90a68cd5..ffc9c439 100644
--- a/python/src/nanoarrow/_utils.pyi
+++ b/python/requirements-stubs.txt
@@ -15,24 +15,7 @@
# specific language governing permissions and limitations
# under the License.
-import _cython_3_0_11
-from typing import ClassVar
-
-__pyx_capi__: dict
-__reduce_cython__: _cython_3_0_11.cython_function_or_method
-__setstate_cython__: _cython_3_0_11.cython_function_or_method
-__test__: dict
-c_version: _cython_3_0_11.cython_function_or_method
-get_pyobject_buffer_count: _cython_3_0_11.cython_function_or_method
-obj_is_buffer: _cython_3_0_11.cython_function_or_method
-obj_is_capsule: _cython_3_0_11.cython_function_or_method
-
-class Error:
- __pyx_vtable__: ClassVar[PyCapsule] = ...
- @classmethod
- def __init__(cls, *args, **kwargs) -> None:
- """Create and return a new object. See help(type) for accurate
signature."""
- def __reduce__(self): ...
-
-class NanoarrowException(RuntimeError):
- def __init__(self, *args, **kwargs) -> None: ...
+# Keep Black in sync with .pre-commit-config.yaml.
+black==22.3.0
+Cython==3.3.1
+mypy==2.4.1
diff --git a/python/src/nanoarrow/_array.pyi b/python/src/nanoarrow/_array.pyi
index aa3d8a71..88f57044 100644
--- a/python/src/nanoarrow/_array.pyi
+++ b/python/src/nanoarrow/_array.pyi
@@ -15,19 +15,23 @@
# specific language governing permissions and limitations
# under the License.
-import _cython_3_0_11
import nanoarrow._device
from _typeshed import Incomplete
from nanoarrow._device import DeviceType as DeviceType
-from typing import ClassVar
+from typing import Iterable
DEVICE_CPU: nanoarrow._device.Device
-__reduce_cython__: _cython_3_0_11.cython_function_or_method
-__setstate_cython__: _cython_3_0_11.cython_function_or_method
-__test__: dict
class CArray:
- __pyx_vtable__: ClassVar[PyCapsule] = ...
+ """Low-level ArrowArray wrapper
+
+ This object is a literal wrapper around a read-only ArrowArray. It
provides field accessors
+ that return Python objects and handles the C Data interface lifecycle
(i.e., initialized
+ ArrowArray structures are always released).
+
+ See `nanoarrow.c_array()` for construction and usage examples.
+ """
+
buffers: Incomplete
children: Incomplete
device_id: Incomplete
@@ -44,14 +48,14 @@ class CArray:
def __init__(cls, *args, **kwargs) -> None:
"""Create and return a new object. See help(type) for accurate
signature."""
@staticmethod
- def allocate(*args, **kwargs):
+ def allocate(schema) -> CArray:
"""Allocate a released ArrowArray"""
- def child(self, *args, **kwargs): ...
- def is_valid(self, *args, **kwargs):
+ def child(self, i): ...
+ def is_valid(self) -> bool:
"""Check for a non-null and non-released underlying ArrowArray"""
- def view(self, *args, **kwargs):
+ def view(self) -> CArrayView:
"""Allocate a :class:`CArrayView` to access the buffers of this
array"""
- def __arrow_c_array__(self, *args, **kwargs):
+ def __arrow_c_array__(self, requested_schema=...):
"""
Get a pair of PyCapsules containing a C ArrowArray representation of
the object.
@@ -74,20 +78,27 @@ class CArray:
def __reduce__(self): ...
class CArrayBuilder:
+ """Helper for constructing an ArrowArray
+
+ The primary function of this class is to wrap the nanoarrow C library calls
+ that build up the components of an ArrowArray.
+ """
+
@classmethod
def __init__(cls, *args, **kwargs) -> None:
"""Create and return a new object. See help(type) for accurate
signature."""
@staticmethod
- def allocate(*args, **kwargs):
+ def allocate(device=...):
"""Create a CArrayBuilder
Allocates memory for an ArrowArray and populates it with nanoarrow's
ArrowArray private_data/release callback implementation. This should
usually be followed by :meth:`init_from_type` or
:meth:`init_from_schema`.
"""
- def append_bytes(self, *args, **kwargs): ...
- def append_strings(self, *args, **kwargs): ...
- def finish(self, *args, **kwargs):
+ def append_bytes(self, obj: Iterable[object]) -> CArrayBuilder: ...
+ def append_strings(self, obj: Iterable[str | None]) -> CArrayBuilder: ...
+ def ensure_buffers(self, n_buffers) -> CArrayBuilder: ...
+ def finish(self, validation_level=...) -> CArray:
"""Finish building this array
Performs any steps required to return a valid ArrowArray and optionally
@@ -101,22 +112,22 @@ class CArrayBuilder:
validation if possible. Validation may not be possible if children
were set that were not created by nanoarrow.
"""
- def finish_device(self, *args, **kwargs):
+ def finish_device(self):
"""Finish building this array and export to an ArrowDeviceArray
Calls :meth:`finish`, propagating device information into an
ArrowDeviceArray.
"""
- def init_from_schema(self, *args, **kwargs): ...
- def init_from_type(self, *args, **kwargs): ...
- def is_empty(self, *args, **kwargs):
+ def init_from_schema(self, schema) -> CArrayBuilder: ...
+ def init_from_type(self, type_id) -> CArrayBuilder: ...
+ def is_empty(self) -> bool:
"""Check if any items have been appended to this builder"""
- def resolve_null_count(self, *args, **kwargs):
+ def resolve_null_count(self) -> CArrayBuilder:
"""Ensure the output null count is synchronized with existing buffers
Note that this will not attempt to access non-CPU buffers such that
:attr:`null_count` might still be -1 after calling this method.
"""
- def set_buffer(self, *args, **kwargs):
+ def set_buffer(self, i, buffer, move=...) -> CArrayBuilder:
"""Set an ArrowArray buffer
Sets a buffer of this ArrowArray such the pointer at array->buffers[i]
is
@@ -127,7 +138,7 @@ class CArrayBuilder:
is False (the default), this function will a make a shallow copy via
another
layer of Python object wrapping.
"""
- def set_child(self, *args, **kwargs):
+ def set_child(self, i, c_array, move=...) -> CArrayBuilder:
"""Set an ArrowArray child
Set a child of this array by performing a show copy or optionally
@@ -135,10 +146,10 @@ class CArrayBuilder:
must have been initialized before this call by initializing this
builder with a schema containing the correct number of children.
"""
- def set_length(self, *args, **kwargs): ...
- def set_null_count(self, *args, **kwargs): ...
- def set_offset(self, *args, **kwargs): ...
- def start_appending(self, *args, **kwargs):
+ def set_length(self, length) -> CArrayBuilder: ...
+ def set_null_count(self, null_count) -> CArrayBuilder: ...
+ def set_offset(self, offset) -> CArrayBuilder: ...
+ def start_appending(self) -> CArrayBuilder:
"""Use append mode for building this ArrowArray
Calling this method is required to produce a valid array prior to
calling
@@ -147,6 +158,15 @@ class CArrayBuilder:
def __reduce__(self): ...
class CArrayView:
+ """Low-level ArrowArrayView wrapper
+
+ This object is a literal wrapper around an ArrowArrayView. It provides
field accessors
+ that return Python objects and handles the structure lifecycle (i.e.,
initialized
+ ArrowArrayView structures are always released).
+
+ See `nanoarrow.c_array_view()` for construction and usage examples.
+ """
+
buffers: Incomplete
children: Incomplete
dictionary: Incomplete
@@ -161,18 +181,27 @@ class CArrayView:
@classmethod
def __init__(cls, *args, **kwargs) -> None:
"""Create and return a new object. See help(type) for accurate
signature."""
- def buffer(self, *args, **kwargs): ...
- def buffer_type(self, *args, **kwargs): ...
- def child(self, *args, **kwargs): ...
+ def buffer(self, i): ...
+ def buffer_type(self, i): ...
+ def child(self, i): ...
@staticmethod
- def from_array(*args, **kwargs): ...
+ def from_array(array, device=...): ...
@staticmethod
- def from_schema(*args, **kwargs): ...
+ def from_schema(schema): ...
def __len__(self) -> int:
"""Return len(self)."""
def __reduce__(self): ...
class CDeviceArray:
+ """Low-level ArrowDeviceArray wrapper
+
+ This object is a literal wrapper around an ArrowDeviceArray. It provides
field accessors
+ that return Python objects and handles the structure lifecycle (i.e.,
initialized
+ ArrowDeviceArray structures are always released).
+
+ See `nanoarrow.device.c_device_array()` for construction and usage
examples.
+ """
+
array: Incomplete
device_id: Incomplete
device_type: Incomplete
@@ -181,7 +210,7 @@ class CDeviceArray:
@classmethod
def __init__(cls, *args, **kwargs) -> None:
"""Create and return a new object. See help(type) for accurate
signature."""
- def view(self, *args, **kwargs): ...
- def __arrow_c_array__(self, *args, **kwargs): ...
- def __arrow_c_device_array__(self, *args, **kwargs): ...
+ def view(self) -> CArrayView: ...
+ def __arrow_c_array__(self, requested_schema=...): ...
+ def __arrow_c_device_array__(self, requested_schema=...): ...
def __reduce__(self): ...
diff --git a/python/src/nanoarrow/_array.pyx b/python/src/nanoarrow/_array.pyx
index a30ac372..239982d5 100644
--- a/python/src/nanoarrow/_array.pyx
+++ b/python/src/nanoarrow/_array.pyx
@@ -634,7 +634,7 @@ cdef class CArrayBuilder:
return self
- def append_bytes(self, obj: Iterable[Union[str, None]]) -> CArrayBuilder:
+ def append_bytes(self, obj: Iterable[object]) -> CArrayBuilder:
cdef Py_buffer buffer
cdef ArrowBufferView item
diff --git a/python/src/nanoarrow/_array_stream.pyi
b/python/src/nanoarrow/_array_stream.pyi
index b0fca6ef..78a66870 100644
--- a/python/src/nanoarrow/_array_stream.pyi
+++ b/python/src/nanoarrow/_array_stream.pyi
@@ -15,24 +15,31 @@
# specific language governing permissions and limitations
# under the License.
-import _cython_3_0_11
-import types
from _typeshed import Incomplete
-from typing import ClassVar
-
-__reduce_cython__: _cython_3_0_11.cython_function_or_method
-__setstate_cython__: _cython_3_0_11.cython_function_or_method
-__test__: dict
+from nanoarrow._array import CArray
+from nanoarrow._schema import CSchema
+from typing import Iterable
class CArrayStream:
+ """Low-level ArrowArrayStream wrapper
+
+ This object is a literal wrapper around an ArrowArrayStream. It provides
methods that
+ that wrap the underlying C callbacks and handles the C Data interface
lifecycle
+ (i.e., initialized ArrowArrayStream structures are always released).
+
+ See `nanoarrow.c_array_stream()` for construction and usage examples.
+ """
+
@classmethod
def __init__(cls, *args, **kwargs) -> None:
"""Create and return a new object. See help(type) for accurate
signature."""
@staticmethod
- def allocate(*args, **kwargs):
+ def allocate() -> CArrayStream:
"""Allocate a released ArrowArrayStream"""
@staticmethod
- def from_c_arrays(*args, **kwargs):
+ def from_c_arrays(
+ arrays: list[CArray], schema, move=..., validate=...
+ ) -> CArrayStream:
"""Create an ArrowArrayStream from an existing set of arrays
Given a previously resolved list of arrays, create an ArrowArrayStream
@@ -54,22 +61,22 @@ class CArrayStream:
If True, enforce type equality between the provided schema and the
schema
of each array.
"""
- def get_next(self, *args, **kwargs):
+ def get_next(self) -> CArray:
"""Get the next Array from this stream
Raises StopIteration when there are no more arrays in this stream.
"""
- def get_schema(self, *args, **kwargs):
+ def get_schema(self) -> CSchema:
"""Get the schema associated with this stream
Calling this method will always issue a call to the underlying stream's
get_schema callback.
"""
- def is_valid(self, *args, **kwargs):
+ def is_valid(self) -> bool:
"""Check for a non-null and non-released underlying ArrowArrayStream"""
- def release(self, *args, **kwargs):
+ def release(self):
"""Explicitly call the release callback of this stream"""
- def __arrow_c_stream__(self, *args, **kwargs):
+ def __arrow_c_stream__(self, requested_schema=...):
"""
Export the stream as an Arrow C stream PyCapsule.
@@ -84,41 +91,43 @@ class CArrayStream:
PyCapsule
"""
def __enter__(self): ...
- def __exit__(
- self,
- type: type[BaseException] | None,
- value: BaseException | None,
- traceback: types.TracebackType | None,
- ): ...
+ def __exit__(self, *args, **kwargs): ...
def __iter__(self):
"""Implement iter(self)."""
def __next__(self): ...
def __reduce__(self): ...
class CMaterializedArrayStream:
- __pyx_vtable__: ClassVar[PyCapsule] = ...
+ """Optimized representation of a fully consumed ArrowArrayStream
+
+ This class provides a data structure similar to pyarrow's ChunkedArray
+ where each consumed array is a referenced-counted shared array. This
+ class wraps the utilities provided by the nanoarrow C library to iterate
+ over and facilitate log(n) random access to items in this container.
+ """
+
arrays: Incomplete
n_arrays: Incomplete
schema: Incomplete
@classmethod
def __init__(cls, *args, **kwargs) -> None:
"""Create and return a new object. See help(type) for accurate
signature."""
- def array(self, *args, **kwargs): ...
- def child(self, *args, **kwargs): ...
+ def array(self, i) -> CArray: ...
+ def child(self, i) -> CMaterializedArrayStream: ...
@staticmethod
- def from_c_array(*args, **kwargs):
+ def from_c_array(array) -> CMaterializedArrayStream:
""" "Create a materialized array stream from a single array"""
@staticmethod
- def from_c_array_stream(*args, **kwargs):
+ def from_c_array_stream(stream) -> CMaterializedArrayStream:
""" "Create a materialized array stream from an unmaterialized
ArrowArrayStream"""
@staticmethod
- def from_c_arrays(*args, **kwargs):
+ def from_c_arrays(arrays: Iterable[CArray], schema, validate=...):
""" "Create a materialized array stream from an existing iterable of
arrays
This is slightly more efficient than creating a stream and then
consuming it
because the implementation can avoid a shallow copy of each array.
"""
- def __arrow_c_stream__(self, *args, **kwargs): ...
+ def __arrow_c_stream__(self, requested_schema=...): ...
def __getitem__(self, index):
"""Return self[key]."""
def __iter__(self):
diff --git a/python/src/nanoarrow/_buffer.pyi b/python/src/nanoarrow/_buffer.pyi
index aed13289..9872eee3 100644
--- a/python/src/nanoarrow/_buffer.pyi
+++ b/python/src/nanoarrow/_buffer.pyi
@@ -15,18 +15,21 @@
# specific language governing permissions and limitations
# under the License.
-import _cython_3_0_11
import nanoarrow._device
from _typeshed import Incomplete
-from typing import ClassVar
DEVICE_CPU: nanoarrow._device.Device
-__reduce_cython__: _cython_3_0_11.cython_function_or_method
-__setstate_cython__: _cython_3_0_11.cython_function_or_method
-__test__: dict
class CBuffer:
- __pyx_vtable__: ClassVar[PyCapsule] = ...
+ """Wrapper around readable owned buffer content
+
+ Like the CBufferView, the CBuffer represents readable buffer content;
however,
+ unlike the CBufferView, the CBuffer always represents a valid ArrowBuffer
C object.
+ Whereas the CBufferView is primarily concerned with accessing the contents
of a
+ buffer, the CBuffer is primarily concerned with managing ownership of an
external
+ buffer such that it exported as an Arrow array.
+ """
+
data_type: Incomplete
data_type_id: Incomplete
device: Incomplete
@@ -38,13 +41,13 @@ class CBuffer:
@classmethod
def __init__(cls, *args, **kwargs) -> None:
"""Create and return a new object. See help(type) for accurate
signature."""
- def element(self, *args, **kwargs): ...
- def elements(self, *args, **kwargs): ...
+ def element(self, i): ...
+ def elements(self, offset=..., length=...): ...
@staticmethod
- def empty(*args, **kwargs):
+ def empty():
"""Create an empty CBuffer"""
@staticmethod
- def from_dlpack(*args, **kwargs):
+ def from_dlpack(obj, stream=...) -> CBuffer:
"""Create a CBuffer using the DLPack protocol
Wraps a tensor from an external library as a CBuffer that can be used
@@ -62,7 +65,7 @@ class CBuffer:
or more buffers in this way).
"""
@staticmethod
- def from_pybuffer(*args, **kwargs):
+ def from_pybuffer(obj) -> CBuffer:
"""Create a CBuffer using the Python buffer protocol
Wraps a buffer using the Python buffer protocol as a CBuffer that can
be
@@ -73,7 +76,7 @@ class CBuffer:
obj : buffer-like
The object on which to invoke the Python buffer protocol
"""
- def view(self, *args, **kwargs):
+ def view(self):
"""Export this buffer as a CBufferView
Returns a :class:`CBufferView` of this buffer. After calling this
@@ -95,7 +98,17 @@ class CBuffer:
"""Release the buffer object that exposes the underlying memory of the
object."""
class CBufferBuilder:
- __pyx_vtable__: ClassVar[PyCapsule] = ...
+ """Wrapper around writable CPU buffer content
+
+ This class provides a growable type-aware buffer that can be used
+ to create a typed buffer from a Python iterable. This method of
+ creating a buffer is usually slower than constructors like
+ ``array.array()`` or ``numpy.array()``; however, this class supports
+ all Arrow types with a single data buffer (e.g., boolean bitmaps,
+ float16, intervals, fixed-size binary), some of which are not supported
+ by other constructors.
+ """
+
capacity_bytes: Incomplete
format: Incomplete
itemsize: Incomplete
@@ -103,14 +116,14 @@ class CBufferBuilder:
@classmethod
def __init__(cls, *args, **kwargs) -> None:
"""Create and return a new object. See help(type) for accurate
signature."""
- def advance(self, *args, **kwargs):
+ def advance(self, additional_bytes):
"""Manually increase :attr:`size_bytes` by ``additional_bytes``
This can be used after writing to the buffer using the buffer protocol
to ensure that :attr:`size_bytes` accurately reflects the number of
bytes written to the buffer.
"""
- def finish(self, *args, **kwargs):
+ def finish(self):
"""Finish building this buffer
Performs any steps required to finish building this buffer and
@@ -118,16 +131,16 @@ class CBufferBuilder:
on this object after it has been finished is not currently
defined (but should not crash).
"""
- def reserve_bytes(self, *args, **kwargs):
+ def reserve_bytes(self, additional_bytes):
"""Ensure that the underlying buffer has space for ``additional_bytes``
more bytes to be written"""
- def set_data_type(self, *args, **kwargs):
+ def set_data_type(self, type_id, element_size_bits=...):
"""Set the data type used to interpret elements in
:meth:`write_elements`."""
- def set_format(self, *args, **kwargs):
+ def set_format(self, format):
"""Set the Python buffer format used to interpret elements in
:meth:`write_elements`.
"""
- def write(self, *args, **kwargs):
+ def write(self, content):
"""Write bytes to this buffer
Writes the bytes of ``content`` without considering the element type of
@@ -135,7 +148,7 @@ class CBufferBuilder:
This method returns the number of bytes that were written.
"""
- def write_elements(self, *args, **kwargs):
+ def write_elements(self, obj):
""" "Write an iterable of elements to this buffer
Writes the elements of iterable ``obj`` according to the binary
@@ -145,7 +158,7 @@ class CBufferBuilder:
This method returns the number of elements that were written.
"""
- def write_fill(self, *args, **kwargs):
+ def write_fill(self, value, size_bytes):
"""Write fill bytes to this buffer
Appends the byte ``value`` to this buffer ``size_bytes`` times.
@@ -159,7 +172,14 @@ class CBufferBuilder:
"""Release the buffer object that exposes the underlying memory of the
object."""
class CBufferView:
- __pyx_vtable__: ClassVar[PyCapsule] = ...
+ """Wrapper for Array buffer content
+
+ This object is a Python wrapper around a buffer held by an Array.
+ It implements the Python buffer protocol and is best accessed through
+ another implementor (e.g., `np.array(array_view.buffers[1])`)). Note that
+ this buffer content does not apply any parent offset.
+ """
+
data_type: Incomplete
data_type_id: Incomplete
device: Incomplete
@@ -171,15 +191,15 @@ class CBufferView:
@classmethod
def __init__(cls, *args, **kwargs) -> None:
"""Create and return a new object. See help(type) for accurate
signature."""
- def copy(self, *args, **kwargs): ...
- def copy_into(self, *args, **kwargs): ...
- def element(self, *args, **kwargs): ...
- def elements(self, *args, **kwargs): ...
- def unpack_bits(self, *args, **kwargs): ...
- def unpack_bits_into(self, *args, **kwargs): ...
+ def copy(self, offset=..., length=...): ...
+ def copy_into(self, dest, offset=..., length=..., dest_offset=...): ...
+ def element(self, i): ...
+ def elements(self, offset=..., length=...): ...
+ def unpack_bits(self, offset=..., length=...): ...
+ def unpack_bits_into(self, dest, offset=..., length=..., dest_offset=...):
...
def __buffer__(self, *args, **kwargs):
"""Return a buffer object that exposes the underlying memory of the
object."""
- def __dlpack__(self, *args, **kwargs):
+ def __dlpack__(self, stream=...):
"""
Export CBufferView as a DLPack capsule.
@@ -195,7 +215,7 @@ class CBufferView:
capsule : PyCapsule
A DLPack capsule for the array, pointing to a DLManagedTensor.
"""
- def __dlpack_device__(self, *args, **kwargs):
+ def __dlpack_device__(self):
"""
Return the DLPack device tuple this CBufferView resides on.
@@ -217,14 +237,23 @@ class CBufferView:
"""Release the buffer object that exposes the underlying memory of the
object."""
class NoneAwareWrapperIterator:
- __pyx_vtable__: ClassVar[PyCapsule] = ...
+ """Nullable iterator wrapper
+
+ This class wraps an iterable ``obj`` that might contain ``None`` values
+ such that the iterable provided by this class contains "empty" (but valid)
+ values. After ``obj`` has been completely consumed, one can call
+ ``finish()`` to obtain the resulting bitmap. This is useful for passing
+ iterables that might contain None to tools that cannot handle them
+ (e.g., struct.pack(), array.array()).
+ """
+
@classmethod
def __init__(cls, *args, **kwargs) -> None:
"""Create and return a new object. See help(type) for accurate
signature."""
- def finish(self, *args, **kwargs):
+ def finish(self):
"""Obtain the total count, null count, and validity bitmap after
consuming this iterable."""
- def reserve(self, *args, **kwargs): ...
+ def reserve(self, additional_elements): ...
def __iter__(self):
"""Implement iter(self)."""
def __reduce__(self): ...
diff --git a/python/src/nanoarrow/_device.pyi b/python/src/nanoarrow/_device.pyi
index 4d2c2079..8016219c 100644
--- a/python/src/nanoarrow/_device.pyi
+++ b/python/src/nanoarrow/_device.pyi
@@ -15,24 +15,26 @@
# specific language governing permissions and limitations
# under the License.
-import _cython_3_0_11
-import enum
from _typeshed import Incomplete
-from typing import Callable, ClassVar
+from enum import Enum as _Enum
DEVICE_CPU: Device
-__reduce_cython__: _cython_3_0_11.cython_function_or_method
-__setstate_cython__: _cython_3_0_11.cython_function_or_method
-__test__: dict
class CSharedSyncEvent:
- __pyx_vtable__: ClassVar[PyCapsule] = ...
@classmethod
def __init__(cls, *args, **kwargs) -> None:
"""Create and return a new object. See help(type) for accurate
signature."""
def __reduce__(self): ...
class Device:
+ """ArrowDevice wrapper
+
+ The ArrowDevice structure is a nanoarrow internal struct (i.e.,
+ not ABI stable) that contains callbacks for device operations
+ beyond its type and identifier (e.g., copy buffers to or from
+ a device).
+ """
+
device_id: Incomplete
device_type: Incomplete
device_type_id: Incomplete
@@ -40,7 +42,7 @@ class Device:
def __init__(cls, *args, **kwargs) -> None:
"""Create and return a new object. See help(type) for accurate
signature."""
@staticmethod
- def resolve(*args, **kwargs): ...
+ def resolve(device_type, device_id): ...
def __eq__(self, other: object) -> bool:
"""Return self==value."""
def __ge__(self, other: object) -> bool:
@@ -55,27 +57,28 @@ class Device:
"""Return self!=value."""
def __reduce__(self): ...
-class DeviceType(enum.Enum):
- __new__: ClassVar[Callable] = ...
- CPU: ClassVar[DeviceType] = ...
- CUDA: ClassVar[DeviceType] = ...
- CUDA_HOST: ClassVar[DeviceType] = ...
- CUDA_MANAGED: ClassVar[DeviceType] = ...
- EXT_DEV: ClassVar[DeviceType] = ...
- HEXAGON: ClassVar[DeviceType] = ...
- METAL: ClassVar[DeviceType] = ...
- ONEAPI: ClassVar[DeviceType] = ...
- OPENCL: ClassVar[DeviceType] = ...
- ROCM: ClassVar[DeviceType] = ...
- ROCM_HOST: ClassVar[DeviceType] = ...
- VPI: ClassVar[DeviceType] = ...
- VULKAN: ClassVar[DeviceType] = ...
- WEBGPU: ClassVar[DeviceType] = ...
- _generate_next_value_: ClassVar[Callable] = ...
- _member_map_: ClassVar[dict] = ...
- _member_names_: ClassVar[list] = ...
- _member_type_: ClassVar[type[object]] = ...
- _unhashable_values_: ClassVar[list] = ...
- _use_args_: ClassVar[bool] = ...
- _value2member_map_: ClassVar[dict] = ...
- _value_repr_: ClassVar[None] = ...
+class DeviceType(_Enum):
+ """
+ An enumerator providing access to the device constant values
+ defined in the Arrow C Device interface. Unlike the other enum
+ accessors, this Python Enum is defined in Cython so that we can use
+ the bulit-in functionality to do better printing of device identifiers
+ for classes defined in Cython. Unlike the other enums, users don't
+ typically need to specify these (but would probably like them printed
+ nicely).
+ """
+
+ CPU = 1
+ CUDA = 2
+ CUDA_HOST = 3
+ OPENCL = 4
+ VULKAN = 7
+ METAL = 8
+ VPI = 9
+ ROCM = 10
+ ROCM_HOST = 11
+ EXT_DEV = 12
+ CUDA_MANAGED = 13
+ ONEAPI = 14
+ WEBGPU = 15
+ HEXAGON = 16
diff --git a/python/src/nanoarrow/_ipc_lib.pyi
b/python/src/nanoarrow/_ipc_lib.pyi
index 620dcba4..ee42b3e1 100644
--- a/python/src/nanoarrow/_ipc_lib.pyi
+++ b/python/src/nanoarrow/_ipc_lib.pyi
@@ -15,22 +15,16 @@
# specific language governing permissions and limitations
# under the License.
-import _cython_3_0_11
from _typeshed import Incomplete
-__reduce_cython__: _cython_3_0_11.cython_function_or_method
-__setstate_cython__: _cython_3_0_11.cython_function_or_method
-__test__: dict
-init_array_stream: _cython_3_0_11.cython_function_or_method
-
class CIpcInputStream:
@classmethod
def __init__(cls, *args, **kwargs) -> None:
"""Create and return a new object. See help(type) for accurate
signature."""
@staticmethod
- def from_readable(*args, **kwargs): ...
- def is_valid(self, *args, **kwargs): ...
- def release(self, *args, **kwargs): ...
+ def from_readable(obj, close_obj=...): ...
+ def is_valid(self): ...
+ def release(self): ...
def __reduce__(self): ...
class CIpcOutputStream:
@@ -38,21 +32,21 @@ class CIpcOutputStream:
def __init__(cls, *args, **kwargs) -> None:
"""Create and return a new object. See help(type) for accurate
signature."""
@staticmethod
- def from_writable(*args, **kwargs): ...
- def is_valid(self, *args, **kwargs): ...
- def release(self, *args, **kwargs): ...
+ def from_writable(obj, close_obj=...): ...
+ def is_valid(self): ...
+ def release(self): ...
def __reduce__(self): ...
class CIpcWriter:
@classmethod
def __init__(cls, *args, **kwargs) -> None:
"""Create and return a new object. See help(type) for accurate
signature."""
- def is_valid(self, *args, **kwargs): ...
- def release(self, *args, **kwargs): ...
- def write_array_stream(self, *args, **kwargs): ...
- def write_array_view(self, *args, **kwargs): ...
- def write_end_of_stream(self, *args, **kwargs): ...
- def write_schema(self, *args, **kwargs): ...
+ def is_valid(self): ...
+ def release(self): ...
+ def write_array_stream(self, stream_addr): ...
+ def write_array_view(self, array_view): ...
+ def write_end_of_stream(self): ...
+ def write_schema(self, schema): ...
def __reduce__(self): ...
class PyStreamPrivate:
@@ -61,7 +55,7 @@ class PyStreamPrivate:
@classmethod
def __init__(cls, *args, **kwargs) -> None:
"""Create and return a new object. See help(type) for accurate
signature."""
- def set_buffer(self, *args, **kwargs): ...
+ def set_buffer(self, addr, size_bytes): ...
def __buffer__(self, *args, **kwargs):
"""Return a buffer object that exposes the underlying memory of the
object."""
def __len__(self) -> int:
@@ -69,3 +63,5 @@ class PyStreamPrivate:
def __reduce__(self): ...
def __release_buffer__(self, *args, **kwargs):
"""Release the buffer object that exposes the underlying memory of the
object."""
+
+def init_array_stream(input_stream, out): ...
diff --git a/python/src/nanoarrow/_schema.pyi b/python/src/nanoarrow/_schema.pyi
index 218fb783..fd8f08ff 100644
--- a/python/src/nanoarrow/_schema.pyi
+++ b/python/src/nanoarrow/_schema.pyi
@@ -15,17 +15,15 @@
# specific language governing permissions and limitations
# under the License.
-import _cython_3_0_11
from _typeshed import Incomplete
-from typing import ClassVar
-
-__pyx_capi__: dict
-__reduce_cython__: _cython_3_0_11.cython_function_or_method
-__setstate_cython__: _cython_3_0_11.cython_function_or_method
-__test__: dict
-assert_type_equal: _cython_3_0_11.cython_function_or_method
+from typing import ClassVar, Iterable, Mapping
class CArrowTimeUnit:
+ """
+ Wrapper around ArrowTimeUnit to provide implementations in Python access
+ to the values.
+ """
+
MICRO: ClassVar[int] = ...
MILLI: ClassVar[int] = ...
NANO: ClassVar[int] = ...
@@ -34,10 +32,13 @@ class CArrowTimeUnit:
def __init__(cls, *args, **kwargs) -> None:
"""Create and return a new object. See help(type) for accurate
signature."""
def __reduce__(self): ...
- def __reduce_cython__(self, *args, **kwargs): ...
- def __setstate_cython__(self, *args, **kwargs): ...
class CLayout:
+ """Abstract buffer information for Arrow types
+
+ Provides accessors for buffer counts, types, and attributes.
+ """
+
buffer_data_type_id: Incomplete
child_size_elements: Incomplete
element_size_bits: Incomplete
@@ -48,6 +49,15 @@ class CLayout:
def __reduce__(self): ...
class CSchema:
+ """Low-level ArrowSchema wrapper
+
+ This object is a literal wrapper around a read-only ArrowSchema. It
provides field accessors
+ that return Python objects and handles the C Data interface lifecycle
(i.e., initialized
+ ArrowSchema structures are always released).
+
+ See ``nanoarrow.c_schema()`` for construction and usage examples.
+ """
+
children: Incomplete
dictionary: Incomplete
flags: Incomplete
@@ -59,13 +69,24 @@ class CSchema:
def __init__(cls, *args, **kwargs) -> None:
"""Create and return a new object. See help(type) for accurate
signature."""
@staticmethod
- def allocate(*args, **kwargs):
+ def allocate() -> CSchema:
"""Allocate a released CSchema"""
- def child(self, *args, **kwargs): ...
- def is_valid(self, *args, **kwargs):
+ def child(self, i): ...
+ def is_valid(self) -> bool:
"""Check for a non-null and non-released underlying ArrowSchema"""
- def modify(self, *args, **kwargs): ...
- def type_equals(self, *args, **kwargs):
+ def modify(
+ self,
+ *,
+ format=...,
+ name=...,
+ flags=...,
+ nullable=...,
+ metadata=...,
+ children=...,
+ dictionary=...,
+ validate=...
+ ) -> CSchema: ...
+ def type_equals(self, other, check_nullability: bool = ...) -> bool:
"""Test two schemas for data type equality
Checks two CSchema objects for type equality (i.e., that an array with
@@ -81,45 +102,62 @@ class CSchema:
If True, actual and expected will be considered equal if their
data type information and marked nullability are identical.
"""
- def __arrow_c_schema__(self, *args, **kwargs):
+ def __arrow_c_schema__(self):
"""
Export to a ArrowSchema PyCapsule
"""
- def __deepcopy__(self): ...
+ def __deepcopy__(self, memo=...) -> CSchema: ...
def __reduce__(self): ...
class CSchemaBuilder:
+ """Helper for constructing an ArrowSchema
+
+ The primary function of this class is to wrap the nanoarrow C library calls
+ that build up the components of an ArrowSchema.
+ """
+
@classmethod
def __init__(cls, *args, **kwargs) -> None:
"""Create and return a new object. See help(type) for accurate
signature."""
@staticmethod
- def allocate(*args, **kwargs):
+ def allocate() -> CSchemaBuilder:
"""Create a CSchemaBuilder
Allocates memory for an ArrowSchema and populates it with nanoarrow's
ArrowSchema private_data/release callback implementation. This should
usually be followed by :meth:`set_type` or :meth:`set_format`.
"""
- def allocate_children(self, *args, **kwargs): ...
- def append_metadata(self, *args, **kwargs):
+ def allocate_children(self, n) -> CSchemaBuilder: ...
+ def append_metadata(self, metadata: Mapping[bytes, bytes]) ->
CSchemaBuilder:
"""Append key/value metadata"""
- def child(self, *args, **kwargs): ...
- def finish(self, *args, **kwargs): ...
- def set_child(self, *args, **kwargs): ...
- def set_dictionary(self, *args, **kwargs): ...
- def set_dictionary_ordered(self, *args, **kwargs): ...
- def set_flags(self, *args, **kwargs): ...
- def set_format(self, *args, **kwargs): ...
- def set_name(self, *args, **kwargs): ...
- def set_nullable(self, *args, **kwargs): ...
- def set_type(self, *args, **kwargs): ...
- def set_type_date_time(self, *args, **kwargs): ...
- def set_type_decimal(self, *args, **kwargs): ...
- def set_type_fixed_size(self, *args, **kwargs): ...
- def validate(self, *args, **kwargs): ...
+ def child(self, i) -> CSchemaBuilder: ...
+ def finish(self) -> CSchema: ...
+ def set_child(self, i, name, child_src) -> CSchemaBuilder: ...
+ def set_dictionary(self, dictionary) -> CSchemaBuilder: ...
+ def set_dictionary_ordered(self, dictionary_ordered) -> CSchemaBuilder: ...
+ def set_flags(self, flags) -> CSchemaBuilder: ...
+ def set_format(self, format) -> CSchemaBuilder: ...
+ def set_map_keys_sorted(self, map_keys_sorted) -> CSchemaBuilder: ...
+ def set_name(self, name) -> CSchemaBuilder: ...
+ def set_nullable(self, nullable) -> CSchemaBuilder: ...
+ def set_type(self, type_id) -> CSchemaBuilder: ...
+ def set_type_date_time(self, type_id, time_unit, timezone) ->
CSchemaBuilder: ...
+ def set_type_decimal(self, type_id, precision, scale) -> CSchemaBuilder:
...
+ def set_type_fixed_size(self, type_id, fixed_size) -> CSchemaBuilder: ...
+ def validate(self) -> CSchemaView: ...
def __reduce__(self): ...
class CSchemaView:
+ """Low-level ArrowSchemaView wrapper
+
+ This object is a literal wrapper around a read-only ArrowSchemaView. It
provides field accessors
+ that return Python objects and handles structure lifecycle. Compared to an
ArrowSchema,
+ the nanoarrow ArrowSchemaView facilitates access to the deserialized
content of an ArrowSchema
+ (e.g., parameter values for parameterized types).
+
+ See `nanoarrow.c_schema_view()` for construction and usage examples.
+ """
+
buffer_format: Incomplete
decimal_bitwidth: Incomplete
decimal_precision: Incomplete
@@ -146,23 +184,31 @@ class CSchemaView:
def __reduce__(self): ...
class SchemaMetadata:
- __pyx_vtable__: ClassVar[PyCapsule] = ...
+ """Dictionary-like wrapper around a lazily-parsed CSchema.metadata string
+
+ The Arrow C Data interface encodes key/value metadata as a bytes-to-bytes
+ mapping using a specific packed binary encoding. This class maintains a
+ reference to the underlying storage and parses it as required. Note that
+ unlike a Python dictionary, ``SchemaMetadata`` can contain duplicate
+ keys.
+ """
+
@classmethod
def __init__(cls, *args, **kwargs) -> None:
"""Create and return a new object. See help(type) for accurate
signature."""
@staticmethod
- def empty(*args, **kwargs):
+ def empty():
"""Create an empty SchemaMetadata with no keys or values"""
- def items(self, *args, **kwargs):
+ def items(self) -> Iterable[tuple[bytes, bytes]]:
"""Iterate over key/value pairs
The result may contain duplicate keys if they exist in the metadata."""
- def keys(self, *args, **kwargs):
+ def keys(self) -> list[bytes]:
"""List meadata keys
The result may contain duplicate keys if they exist in the metadata.
"""
- def values(self, *args, **kwargs):
+ def values(self) -> list[bytes]:
"""List metadata values"""
def __contains__(self, other) -> bool:
"""Return bool(key in self)."""
@@ -177,3 +223,22 @@ class SchemaMetadata:
def __len__(self) -> int:
"""Return len(self)."""
def __reduce__(self): ...
+
+def assert_type_equal(actual, expected, check_nullability):
+ """Test two schemas for data type equality
+
+ Checks two CSchema objects for type equality (i.e., that an array with
+ schema ``actual`` contains elements with the same logical meaning as and
+ array with schema ``expected``). Notably, this excludes metadata from
+ all nodes in the schema.
+
+ Parameters
+ ----------
+ actual : CSchema
+ The schema to be tested for equality
+ expected : CSchema
+ The schema against which to test
+ check_nullability : bool
+ If True, actual and expected will be considered equal if their
+ data type information and marked nullability are identical.
+ """
diff --git a/python/src/nanoarrow/_schema.pyx b/python/src/nanoarrow/_schema.pyx
index d499d1c8..6f9f391c 100644
--- a/python/src/nanoarrow/_schema.pyx
+++ b/python/src/nanoarrow/_schema.pyx
@@ -220,7 +220,7 @@ cdef class SchemaMetadata:
"""List metadata values"""
return [value for _, value in self.items()]
- def items(self) -> Iterable[bytes, bytes]:
+ def items(self) -> Iterable[Tuple[bytes, bytes]]:
"""Iterate over key/value pairs
The result may contain duplicate keys if they exist in the metadata."""
diff --git a/python/src/nanoarrow/_types.pyi b/python/src/nanoarrow/_types.pyi
index e55097b2..b3e4eb05 100644
--- a/python/src/nanoarrow/_types.pyi
+++ b/python/src/nanoarrow/_types.pyi
@@ -15,9 +15,7 @@
# specific language governing permissions and limitations
# under the License.
-import _cython_3_0_11
-import enum
-from typing import Callable, ClassVar
+from enum import IntEnum
BINARY: CArrowType
BINARY_VIEW: CArrowType
@@ -61,80 +59,80 @@ UINT32: CArrowType
UINT64: CArrowType
UINT8: CArrowType
UNINITIALIZED: CArrowType
-__pyx_capi__: dict
-__test__: dict
-has_time_unit: _cython_3_0_11.cython_function_or_method
-is_data_view: _cython_3_0_11.cython_function_or_method
-is_decimal: _cython_3_0_11.cython_function_or_method
-is_fixed_size: _cython_3_0_11.cython_function_or_method
-is_floating_point: _cython_3_0_11.cython_function_or_method
-is_signed_integer: _cython_3_0_11.cython_function_or_method
-is_union: _cython_3_0_11.cython_function_or_method
-is_unsigned_integer: _cython_3_0_11.cython_function_or_method
sys_byteorder: str
-class CArrowType(enum.IntFlag):
- __new__: ClassVar[Callable] = ...
- BINARY: ClassVar[CArrowType] = ...
- BINARY_VIEW: ClassVar[CArrowType] = ...
- BOOL: ClassVar[CArrowType] = ...
- DATE32: ClassVar[CArrowType] = ...
- DATE64: ClassVar[CArrowType] = ...
- DECIMAL128: ClassVar[CArrowType] = ...
- DECIMAL256: ClassVar[CArrowType] = ...
- DENSE_UNION: ClassVar[CArrowType] = ...
- DICTIONARY: ClassVar[CArrowType] = ...
- DOUBLE: ClassVar[CArrowType] = ...
- DURATION: ClassVar[CArrowType] = ...
- EXTENSION: ClassVar[CArrowType] = ...
- FIXED_SIZE_BINARY: ClassVar[CArrowType] = ...
- FIXED_SIZE_LIST: ClassVar[CArrowType] = ...
- FLOAT: ClassVar[CArrowType] = ...
- HALF_FLOAT: ClassVar[CArrowType] = ...
- INT16: ClassVar[CArrowType] = ...
- INT32: ClassVar[CArrowType] = ...
- INT64: ClassVar[CArrowType] = ...
- INT8: ClassVar[CArrowType] = ...
- INTERVAL_DAY_TIME: ClassVar[CArrowType] = ...
- INTERVAL_MONTHS: ClassVar[CArrowType] = ...
- INTERVAL_MONTH_DAY_NANO: ClassVar[CArrowType] = ...
- LARGE_BINARY: ClassVar[CArrowType] = ...
- LARGE_LIST: ClassVar[CArrowType] = ...
- LARGE_STRING: ClassVar[CArrowType] = ...
- LIST: ClassVar[CArrowType] = ...
- MAP: ClassVar[CArrowType] = ...
- NA: ClassVar[CArrowType] = ...
- RUN_END_ENCODED: ClassVar[CArrowType] = ...
- SPARSE_UNION: ClassVar[CArrowType] = ...
- STRING: ClassVar[CArrowType] = ...
- STRING_VIEW: ClassVar[CArrowType] = ...
- STRUCT: ClassVar[CArrowType] = ...
- TIME32: ClassVar[CArrowType] = ...
- TIME64: ClassVar[CArrowType] = ...
- TIMESTAMP: ClassVar[CArrowType] = ...
- UINT16: ClassVar[CArrowType] = ...
- UINT32: ClassVar[CArrowType] = ...
- UINT64: ClassVar[CArrowType] = ...
- UINT8: ClassVar[CArrowType] = ...
- UNINITIALIZED: ClassVar[CArrowType] = ...
- _all_bits_: ClassVar[int] = ...
- _boundary_: ClassVar[enum.FlagBoundary] = ...
- _flag_mask_: ClassVar[int] = ...
- _generate_next_value_: ClassVar[Callable] = ...
- _inverted_: ClassVar[None] = ...
- _member_map_: ClassVar[dict] = ...
- _member_names_: ClassVar[list] = ...
- _member_type_: ClassVar[type[int]] = ...
- _singles_mask_: ClassVar[int] = ...
- _unhashable_values_: ClassVar[list] = ...
- _use_args_: ClassVar[bool] = ...
- _value2member_map_: ClassVar[dict] = ...
- __and__: ClassVar[Callable] = ...
- __invert__: ClassVar[Callable] = ...
- __or__: ClassVar[Callable] = ...
- __rand__: ClassVar[Callable] = ...
- __ror__: ClassVar[Callable] = ...
- __rxor__: ClassVar[Callable] = ...
- __xor__: ClassVar[Callable] = ...
- def __format__(self, *args, **kwargs) -> str:
- """Convert to a string according to format_spec."""
+class CArrowType(IntEnum):
+ """ArrowType enumerator
+
+ This enum makes the type identifier constants available to Cython and
+ Python code as (e.g.) ``_types.UNINITIALIZED``. This removes the need
+ for other modules to import type codes, which in previous versions had
+ led to very long ``from nanoarrow_c cimport`` declarations.
+ """
+
+ UNINITIALIZED = 0
+ NA = 1
+ BOOL = 2
+ UINT8 = 3
+ INT8 = 4
+ UINT16 = 5
+ INT16 = 6
+ UINT32 = 7
+ INT32 = 8
+ UINT64 = 9
+ INT64 = 10
+ HALF_FLOAT = 11
+ FLOAT = 12
+ DOUBLE = 13
+ STRING = 14
+ BINARY = 15
+ FIXED_SIZE_BINARY = 16
+ DATE32 = 17
+ DATE64 = 18
+ TIMESTAMP = 19
+ TIME32 = 20
+ TIME64 = 21
+ INTERVAL_MONTHS = 22
+ INTERVAL_DAY_TIME = 23
+ DECIMAL128 = 24
+ DECIMAL256 = 25
+ LIST = 26
+ STRUCT = 27
+ SPARSE_UNION = 28
+ DENSE_UNION = 29
+ DICTIONARY = 30
+ MAP = 31
+ EXTENSION = 32
+ FIXED_SIZE_LIST = 33
+ DURATION = 34
+ LARGE_STRING = 35
+ LARGE_BINARY = 36
+ LARGE_LIST = 37
+ INTERVAL_MONTH_DAY_NANO = 38
+ RUN_END_ENCODED = 39
+ BINARY_VIEW = 40
+ STRING_VIEW = 41
+
+def has_time_unit(type_id):
+ """Check if type_id represents a type with a time_unit parameter"""
+
+def is_data_view(type_id):
+ """Check if type_id is a binary view or string view type"""
+
+def is_decimal(type_id):
+ """Check if type_id is a decimal type"""
+
+def is_fixed_size(type_id):
+ """Check if type_id is a fixed-size (binary or list) type"""
+
+def is_floating_point(type_id):
+ """Check if type_id is a floating point type"""
+
+def is_signed_integer(type_id):
+ """Check if type_id is an signed integral type"""
+
+def is_union(type_id):
+ """Check if type_id is a union type"""
+
+def is_unsigned_integer(type_id):
+ """Check if type_id is an unsigned integral type"""
diff --git a/python/src/nanoarrow/_utils.pyi b/python/src/nanoarrow/_utils.pyi
index 90a68cd5..9506eed2 100644
--- a/python/src/nanoarrow/_utils.pyi
+++ b/python/src/nanoarrow/_utils.pyi
@@ -15,24 +15,75 @@
# specific language governing permissions and limitations
# under the License.
-import _cython_3_0_11
-from typing import ClassVar
-
-__pyx_capi__: dict
-__reduce_cython__: _cython_3_0_11.cython_function_or_method
-__setstate_cython__: _cython_3_0_11.cython_function_or_method
-__test__: dict
-c_version: _cython_3_0_11.cython_function_or_method
-get_pyobject_buffer_count: _cython_3_0_11.cython_function_or_method
-obj_is_buffer: _cython_3_0_11.cython_function_or_method
-obj_is_capsule: _cython_3_0_11.cython_function_or_method
-
class Error:
- __pyx_vtable__: ClassVar[PyCapsule] = ...
+ """Memory holder for an ArrowError
+
+ ArrowError is the C struct that is optionally passed to nanoarrow functions
+ when a detailed error message might be returned. This class holds a C
+ reference to the object and provides helpers for raising exceptions based
+ on the contained message.
+ """
+
@classmethod
def __init__(cls, *args, **kwargs) -> None:
"""Create and return a new object. See help(type) for accurate
signature."""
def __reduce__(self): ...
class NanoarrowException(RuntimeError):
- def __init__(self, *args, **kwargs) -> None: ...
+ """An error resulting from a call to the nanoarrow C library
+
+ Calls to the nanoarrow C library and/or the Arrow C Stream interface
+ callbacks return an errno error code and sometimes a message with extra
+ detail. This exception wraps a RuntimeError to format a suitable message
+ and store the components of the original error.
+
+ Parameters
+ ----------
+ what : str
+ A string describing the context in which the exception was generated.
+ This is usually the name of a nanoarrow C library function.
+ code : int
+ An errno code (e.g., EINVAL) returned by a nanoarrow C library
function.
+ message : str
+ An optional message (e.g., generated by inspecting an ArrowError).
+ If not provided, a message will be generated based on ``code`` and
``what``.
+ """
+
+ def __init__(self, what, code, message=...): ...
+
+def c_version() -> str:
+ """Return the nanoarrow C library version string"""
+
+def get_pyobject_buffer_count():
+ """Get the current borrowed ArrowBuffer count
+
+ Returns a count of Py_INCREF calls where Py_DECREF has not yet been
+ called on an ArrowBuffer borrowed from a Python object. This function is
+ used to test shallow copy behaviour for leaked PyObject references.
+ """
+
+def obj_is_buffer(obj):
+ """Check if an object implements the Python Buffer protocol
+
+ Provided because this function is not reliably available in all
+ version of PyPy's ctypes implementation.
+
+ Parameters
+ ----------
+ obj : any
+ An object to check
+ """
+
+def obj_is_capsule(obj, name) -> bool:
+ """Check if an object is a PyCapsule
+
+ Provided because this function is not reliably available in all
+ version of PyPy\'s ctypes implementation.
+
+ Parameters
+ ----------
+ obj : any
+ An object to check
+ name : str
+ The PyCapule "name" (e.g., "arrow_array")
+ """
diff --git a/python/tests/test_type_stubs.py b/python/tests/test_type_stubs.py
new file mode 100644
index 00000000..f229a904
--- /dev/null
+++ b/python/tests/test_type_stubs.py
@@ -0,0 +1,67 @@
+# 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 ast
+import importlib
+from pathlib import Path
+
+import pytest
+
+SOURCE_DIR = Path(__file__).resolve().parents[1] / "src" / "nanoarrow"
+
+
+def _public_declarations(body):
+ names = set()
+ for node in body:
+ if isinstance(node, (ast.ClassDef, ast.FunctionDef,
ast.AsyncFunctionDef)):
+ names.add(node.name)
+ elif isinstance(node, ast.AnnAssign) and isinstance(node.target,
ast.Name):
+ names.add(node.target.id)
+ elif isinstance(node, ast.Assign):
+ names.update(
+ target.id for target in node.targets if isinstance(target,
ast.Name)
+ )
+ return {name for name in names if not name.startswith("_")}
+
+
[email protected](
+ "source", sorted(SOURCE_DIR.glob("*.pyx")), ids=lambda f: f.stem
+)
+def test_extension_stub_members(source):
+ module = importlib.import_module(f"nanoarrow.{source.stem}")
+ stub = source.with_suffix(".pyi")
+ tree = ast.parse(stub.read_text(encoding="utf-8"), filename=str(stub))
+ stub_names = _public_declarations(tree.body)
+ runtime_names = {
+ name
+ for name, value in vars(module).items()
+ if not name.startswith("_")
+ and getattr(value, "__module__", None) == module.__name__
+ }
+
+ # Ignore imported members when looking for omissions from the stub.
+ assert runtime_names <= stub_names
+ assert stub_names <= vars(module).keys()
+
+ for node in tree.body:
+ if isinstance(node, ast.ClassDef) and node.name in runtime_names:
+ members = {
+ name
+ for name in vars(getattr(module, node.name))
+ if not name.startswith("_")
+ }
+ assert _public_declarations(node.body) == members, node.name