Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -1556,7 +1556,7 @@ services:
["/arrow/ci/scripts/cpp_build.sh /arrow /build &&
/arrow/ci/scripts/python_build.sh /arrow /build &&
pip install -e /arrow/dev/archery[numpydoc] &&
archery numpydoc --allow-rule GL10,PR01,PR03,PR04,PR05,PR10,RT03,YD01 &&
archery numpydoc --allow-rule GL10,PR01,PR02,PR03,PR04,PR05,PR10,RT03,YD01 &&
/arrow/ci/scripts/python_test.sh /arrow &&
/arrow/ci/scripts/python_test_type_annotations.sh /arrow/python"]

Expand Down
94 changes: 91 additions & 3 deletions dev/archery/archery/lang/python.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,16 +38,33 @@ def _tokenize_signature(s):


def _convert_typehint(tokens):
tokens = list(tokens)
names = []
opening_bracket_reached = False
for token in tokens:
skip_annotation = False
annotation_depth = 0
for i, token in enumerate(tokens):
# omit the tokens before the opening bracket
if not opening_bracket_reached:
if token.string == '(':
opening_bracket_reached = True
else:
continue

if skip_annotation:
if token.string in ('(', '['):
annotation_depth += 1
elif token.string in (')', ']'):
annotation_depth -= 1
elif annotation_depth == 0 and token.string in (',', ')', '='):
# end of the annotation, keep the token itself and continue
# with the default value or the next parameter
skip_annotation = False
else:
# drop the annotation tokens, as annotations are not
# supported by _signature_fromstr
continue

if token.type == 1: # type 1 means NAME token
names.append(token)
else:
Expand All @@ -62,6 +79,19 @@ def _convert_typehint(tokens):
elif len(names) > 2:
raise ValueError('More than two NAME tokens follow each other')
names = []

if token.string == ':' and i + 1 < len(tokens):
# a parameter annotation follows, skip it until the default
# value or the end of the parameter
skip_annotation = True
continue

if (token.string == '*' and i + 1 < len(tokens)
and tokens[i + 1].string == ')'):
# a trailing bare `*` marks keyword-only arguments in cython
# signatures but is not valid python syntax, so drop it
continue

yield (token.type, token.string)


Expand All @@ -82,9 +112,61 @@ def inspect_signature(obj):
"""
cython_signature = obj.__doc__.splitlines()[0]
cython_tokens = _tokenize_signature(cython_signature)
python_tokens = _convert_typehint(cython_tokens)
python_tokens = list(_convert_typehint(cython_tokens))
python_signature = tokenize.untokenize(python_tokens)
return inspect._signature_fromstr(inspect.Signature, obj, python_signature)
try:
return inspect._signature_fromstr(inspect.Signature, obj, python_signature)
except ValueError:
# _signature_fromstr can only evaluate constant default values, so
# retry without the defaults; the parameter names, kinds and their
# order are what matter for the docstring validation
python_signature = tokenize.untokenize(_strip_defaults(python_tokens))
return inspect._signature_fromstr(inspect.Signature, obj, python_signature)


def _strip_defaults(tokens):
"""
Remove the default values from a tokenized parameter list, e.g. turn
``(a=1, b=SomeClass(2))`` into ``(a, b)``. Nested parentheses and
brackets within a default value are dropped as well.
"""
depth = 0
skipping = False
for token in tokens:
string = token[1]
if skipping:
if string in ('(', '[', '{'):
depth += 1
continue
elif string in (')', ']', '}'):
if depth == 0:
# end of the parameter, keep the closing parenthesis
skipping = False
else:
depth -= 1
continue
elif depth == 0 and string == ',':
skipping = False
else:
continue
elif string == '=':
skipping = True
continue
yield token


def _signature_determinable(obj):
"""
Whether the signature of the object could be determined.

Must be called with the patched ``inspect.signature`` active, which
falls back to parsing the signature from the docstring of cython
generated callables.
"""
try:
return inspect.signature(obj) is not None
except Exception:
return False


class NumpyDoc:
Expand Down Expand Up @@ -213,6 +295,12 @@ def callback(obj):
for obj_type, errcode_list
in NumpyDoc.IGNORE_VALIDATION_ERRORS_FOR_TYPE.items()):
continue
if errcode in ('PR01', 'PR02', 'PR03') and not _signature_determinable(obj):
# numpydoc compares the documented parameters against an
# empty signature when the signature could not be
# determined, which would report every documented
# parameter as unknown (PR02)
continue
errors.append((errcode, errmsg))

if len(errors):
Expand Down
148 changes: 148 additions & 0 deletions dev/archery/archery/tests/test_numpydoc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
# 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 pytest

from archery.lang.python import (
_convert_typehint,
_signature_determinable,
_strip_defaults,
inspect_signature,
NumpyDoc,
)


def _tokenize(s):
from archery.lang.python import _tokenize_signature
return _tokenize_signature(s)


def _token_strings(tokens):
# ignore the empty trailing ENDMARKER/NEWLINE tokens
return [string for _, string in tokens if string.strip()]


class FakeCythonCallable:
"""Object whose signature can only be parsed from the docstring."""

def __init__(self, doc):
self.__doc__ = doc


def test_convert_typehint_cython_typehints():
# `bool argument` style cython typehints are dropped
tokens = _convert_typehint(_tokenize("(bool anonymous=False, region=None)"))
assert _token_strings(tokens) == [
'(', 'anonymous', '=', 'False', ',', 'region', '=', 'None', ')'
]


def test_convert_typehint_annotation_with_default():
# annotations are not supported by _signature_fromstr, so they are
# dropped while keeping the default value
tokens = _convert_typehint(_tokenize(
"(retry_strategy: S3RetryStrategy = AwsStandardS3RetryStrategy("
"max_attempts=3), force_virtual_addressing=False)"))
assert _token_strings(tokens) == [
'(', 'retry_strategy', '=', 'AwsStandardS3RetryStrategy', '(',
'max_attempts', '=', '3', ')', ',', 'force_virtual_addressing', '=',
'False', ')'
]


def test_convert_typehint_annotation_without_default():
tokens = _convert_typehint(_tokenize("(a: SomeType, b=None)"))
assert _token_strings(tokens) == [
'(', 'a', ',', 'b', '=', 'None', ')'
]


def test_convert_typehint_trailing_keyword_only_marker():
# a trailing bare `*` is not valid python syntax and is dropped, while a
# keyword-only marker followed by more parameters is kept
tokens = _convert_typehint(_tokenize("(use_mmap=False, *)"))
assert _token_strings(tokens) == [
'(', 'use_mmap', '=', 'False', ',', ')'
]
tokens = _convert_typehint(_tokenize("(access_key=None, *, secret_key=None)"))
assert _token_strings(tokens) == [
'(', 'access_key', '=', 'None', ',', '*', ',', 'secret_key', '=',
'None', ')'
]


def test_strip_defaults():
tokens = list(_convert_typehint(_tokenize(
"(a=1, b=SomeClass(2), *, c='x')")))
assert _token_strings(_strip_defaults(tokens)) == [
'(', 'a', ',', 'b', ',', '*', ',', 'c', ')'
]


def test_inspect_signature_with_non_constant_default():
# _signature_fromstr can only evaluate constant defaults, so parsing
# falls back to a signature without the default values
obj = FakeCythonCallable(
"func(a, b=S3RetryStrategy, retry_strategy: SomeStrategy = "
"AwsStandardS3RetryStrategy(max_attempts=3))\n\n Docstring.")
signature = inspect_signature(obj)
assert list(signature.parameters) == ['a', 'b', 'retry_strategy']


def test_inspect_signature_preserves_defaults_when_evaluable():
obj = FakeCythonCallable(
"func(a=1, b='x')\n\n Docstring.")
signature = inspect_signature(obj)
assert list(signature.parameters) == ['a', 'b']
assert signature.parameters['a'].default == 1


def test_signature_determinable():
doc = NumpyDoc()

with doc._apply_patches():
obj = FakeCythonCallable("func(a, b=None)\n\n Docstring.")
assert _signature_determinable(obj)

# empty signature line, the signature cannot be determined
obj = FakeCythonCallable("\n Docstring without a signature.")
assert not _signature_determinable(obj)


def test_validate_skips_parameter_rules_without_signature():
# numpydoc compares documented parameters against an empty signature
# when the signature cannot be determined, which would report every
# documented parameter as unknown (PR02)
from numpydoc.validate import validate as numpydoc_validate

doc = NumpyDoc()
obj = FakeCythonCallable(
"\n Parameters\n ----------\n a : int\n A param.\n")

with doc._apply_patches():
assert not _signature_determinable(obj)
result = numpydoc_validate(obj)
errors = []
for errcode, errmsg in result['errors']:
# same filtering as NumpyDoc.validate applies
if errcode in ('PR01', 'PR02', 'PR03') and \
not _signature_determinable(obj):
continue
errors.append(errcode)

assert 'PR02' in [code for code, _ in result['errors']]
assert 'PR02' not in errors
30 changes: 17 additions & 13 deletions docs/source/cpp/compute.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1984,27 +1984,31 @@ Structural transforms
The output type is an Array of items for the ``FIRST``/``LAST`` options
and an Array of List of items for the ``ALL`` option.

* \(6) Extract a child value based on a sequence of indices passed in
the options. The validity bitmap of the result will be the
intersection of all intermediate validity bitmaps. For example, for
an array with type ``struct<a: int32, b: struct<c: int64, d:
float64>>``:
* \(6) Extract a child value based on a field reference passed in the
options. The reference can be a sequence of child indices (a
:class:`FieldPath`), a child field name, or a nested sequence of
these (see :class:`FieldRef`; note that a dot path such as ``"b.d"``
must first be parsed with ``FieldRef::FromDotPath``). The validity
bitmap of the result will be the intersection of all intermediate
validity bitmaps. For example, for an array with type
``struct<a: int32, b: struct<c: int64, d: float64>>``:

* An empty sequence of indices yields the original value unchanged.
* The index ``0`` yields an array of type ``int32`` whose validity
bitmap is the intersection of the bitmap for the outermost struct
and the bitmap for the child ``a``.
* The index ``1, 1`` yields an array of type ``float64`` whose
validity bitmap is the intersection of the bitmaps for the
outermost struct, for struct ``b``, and for the child ``d``.
* The index ``0`` or the field name ``"a"`` yields an array of type
``int32`` whose validity bitmap is the intersection of the bitmap
for the outermost struct and the bitmap for the child ``a``.
* The indices ``1, 1`` or the field names ``"b", "d"`` yield an
array of type ``float64`` whose validity bitmap is the
intersection of the bitmaps for the outermost struct, for struct
``b``, and for the child ``d``.

For unions, a validity bitmap is synthesized based on the type
codes. Also, the index is always the child index and not a type code.
Hence for array with type ``sparse_union<2: int32, 7: utf8>``:

* The index ``0`` yields an array of type ``int32``, which is valid
at an index *n* if and only if the child array ``a`` is valid at
index *n* and the type code at index *n* is 2.
at an index *n* if and only if the child array of type ``int32``
is valid at index *n* and the type code at index *n* is 2.
* The indices ``2`` and ``7`` are invalid.

* \(7) Output is true for each list containing a value equal to the second
Expand Down
31 changes: 31 additions & 0 deletions docs/source/python/parquet/parquet_datasets.rst
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,37 @@ combine and write them manually:
... metadata_collector=metadata_collector
... )

If writing a partitioned dataset (i.e. with ``partition_cols``), the partition
columns are not stored in the data files themselves, but are encoded in the
directory names. The collected file metadata therefore has a schema without
the partition columns, and the schema passed to
:func:`~pyarrow.parquet.write_metadata` for the ``_metadata`` file needs to
match that:

.. code-block:: python

>>> # Write a partitioned dataset and collect metadata information of all written files
>>> metadata_collector = []
>>> root_path = "dataset_name_2"
>>> partition_cols = ["one", "two"]
>>> pq.write_to_dataset(table, root_path, partition_cols=partition_cols,
... metadata_collector=metadata_collector)

>>> # Write the ``_common_metadata`` parquet file with the schema of the
>>> # full dataset, including the partition columns
>>> pq.write_metadata(table.schema, root_path + '/_common_metadata')

>>> # Write the ``_metadata`` parquet file with row groups statistics of all
>>> # files. The data files do not include the partition columns, so those
>>> # need to be removed from the schema
>>> file_schema = table.schema
>>> for col in partition_cols:
... file_schema = file_schema.remove(file_schema.get_field_index(col))
>>> pq.write_metadata(
... file_schema, root_path + '/_metadata',
... metadata_collector=metadata_collector
... )

When not using the :func:`~pyarrow.parquet.write_to_dataset` function, but
writing the individual files of the partitioned dataset using
:func:`~pyarrow.parquet.write_table` or :class:`~pyarrow.parquet.ParquetWriter`,
Expand Down
Loading