diff --git a/compose.yaml b/compose.yaml index a7831dbd9f93..5fec2b67fbb0 100644 --- a/compose.yaml +++ b/compose.yaml @@ -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"] diff --git a/dev/archery/archery/lang/python.py b/dev/archery/archery/lang/python.py index f73a2ce44b46..bf739384ed69 100644 --- a/dev/archery/archery/lang/python.py +++ b/dev/archery/archery/lang/python.py @@ -38,9 +38,12 @@ 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 == '(': @@ -48,6 +51,20 @@ def _convert_typehint(tokens): 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: @@ -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) @@ -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: @@ -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): diff --git a/dev/archery/archery/tests/test_numpydoc.py b/dev/archery/archery/tests/test_numpydoc.py new file mode 100644 index 000000000000..c014ee814316 --- /dev/null +++ b/dev/archery/archery/tests/test_numpydoc.py @@ -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 diff --git a/docs/source/cpp/compute.rst b/docs/source/cpp/compute.rst index 4c2df6b3176e..795c2e021d75 100644 --- a/docs/source/cpp/compute.rst +++ b/docs/source/cpp/compute.rst @@ -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>``: +* \(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>``: * 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 diff --git a/docs/source/python/parquet/parquet_datasets.rst b/docs/source/python/parquet/parquet_datasets.rst index 6a47d7867e41..c643786934e9 100644 --- a/docs/source/python/parquet/parquet_datasets.rst +++ b/docs/source/python/parquet/parquet_datasets.rst @@ -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`, diff --git a/python/pyarrow/_s3fs.pyx b/python/pyarrow/_s3fs.pyx index 6317bd3785f1..d8ac815284e2 100644 --- a/python/pyarrow/_s3fs.pyx +++ b/python/pyarrow/_s3fs.pyx @@ -187,17 +187,6 @@ cdef class S3FileSystem(FileSystem): Whether to connect anonymously if access_key and secret_key are None. If true, will not attempt to look up credentials using standard AWS configuration methods. - role_arn : str, default None - AWS Role ARN. If provided instead of access_key and secret_key, - temporary credentials will be fetched by assuming this role. - session_name : str, default None - An optional identifier for the assumed role session. - external_id : str, default None - An optional unique identifier that might be required when you assume - a role in another account. - load_frequency : int, default 900 - The frequency (in seconds) with which temporary credentials from an - assumed role session will be refreshed. region : str, default None AWS region to connect to. If not set, the AWS SDK will attempt to determine the region using heuristics such as environment variables, @@ -221,6 +210,17 @@ cdef class S3FileSystem(FileSystem): default_metadata : mapping or pyarrow.KeyValueMetadata, default None Default metadata for open_output_stream. This will be ignored if non-empty metadata is passed to open_output_stream. + role_arn : str, default None + AWS Role ARN. If provided instead of access_key and secret_key, + temporary credentials will be fetched by assuming this role. + session_name : str, default None + An optional identifier for the assumed role session. + external_id : str, default None + An optional unique identifier that might be required when you assume + a role in another account. + load_frequency : int, default 900 + The frequency (in seconds) with which temporary credentials from an + assumed role session will be refreshed. proxy_options : dict or str, default None If a proxy is used, provide the options here. Supported options are: 'scheme' (str: 'http' or 'https'; required), 'host' (str; required), diff --git a/python/pyarrow/array.pxi b/python/pyarrow/array.pxi index c4862df59783..a23d224c3456 100644 --- a/python/pyarrow/array.pxi +++ b/python/pyarrow/array.pxi @@ -929,6 +929,10 @@ cdef class _PandasConvertible(_Weakrefable): zero_copy_only : bool, default False Raise an ArrowException if this function call would require copying the underlying data. + + When converting a Table or RecordBatch, the columns are converted + as separate pandas blocks (``split_blocks=True``) so that each + column can reference the original Arrow memory. integer_object_nulls : bool, default False Cast integers with nulls to objects date_as_object : bool, default True diff --git a/python/pyarrow/pandas_compat.py b/python/pyarrow/pandas_compat.py index 4ff587b702b6..00a8c943b334 100644 --- a/python/pyarrow/pandas_compat.py +++ b/python/pyarrow/pandas_compat.py @@ -795,6 +795,13 @@ def make_datetimetz(unit, tz): def table_to_dataframe( options, table, categories=None, ignore_metadata=False, types_mapper=None ): + # Zero-copy conversion of a Table or RecordBatch into a DataFrame requires + # one pandas block per column, as a multi-column block cannot reference the + # original Arrow memory; this is only supported with ``split_blocks=True`` + if options.get('zero_copy_only') and not options.get('split_blocks'): + options = dict(options) + options['split_blocks'] = True + all_columns = [] column_indexes = [] attributes = {} diff --git a/python/pyarrow/parquet/core.py b/python/pyarrow/parquet/core.py index 6721eab9a06b..3135f56dd5e3 100644 --- a/python/pyarrow/parquet/core.py +++ b/python/pyarrow/parquet/core.py @@ -1083,6 +1083,9 @@ def __init__(self, where, schema, filesystem=None, compression='snappy', write_statistics=True, use_deprecated_int96_timestamps=None, + coerce_timestamps=None, + allow_truncated_timestamps=False, + data_page_size=None, compression_level=None, use_byte_stream_split=False, column_encoding=None, @@ -1141,6 +1144,9 @@ def __init__(self, where, schema, filesystem=None, use_dictionary=use_dictionary, write_statistics=write_statistics, use_deprecated_int96_timestamps=use_deprecated_int96_timestamps, + coerce_timestamps=coerce_timestamps, + allow_truncated_timestamps=allow_truncated_timestamps, + data_page_size=data_page_size, compression_level=compression_level, use_byte_stream_split=use_byte_stream_split, column_encoding=column_encoding, @@ -2027,16 +2033,33 @@ def read_pandas(source, columns=None, **kwargs): ) -read_pandas.__doc__ = _read_table_docstring.format( - 'Read a Table from Parquet format, also reading DataFrame\n' - 'index values if known in the file metadata', - "\n".join((_read_docstring_common, - """**kwargs - additional options for :func:`read_table`""")), - """pyarrow.Table +read_pandas.__doc__ = """Read a Table from Parquet format, also reading DataFrame +index values if known in the file metadata + +Parameters +---------- +source : str, list of str, pyarrow.NativeFile, or file-like object + If a string is passed, can be a single file name or directory name. If a + list of strings is passed, should be file names. For file-like objects, + only read a single file. Use pyarrow.BufferReader to read a file contained + in a bytes or buffer-like object. +columns : list + If not None, only these columns will be read from the file. A column + name may be a prefix of a nested field, e.g. 'a' will select 'a.b', + 'a.c', and 'a.d.e'. If empty, no columns will be read. Note + that the table will still have the correct num_rows set despite having + no columns. +**kwargs : optional + Additional keyword arguments passed to :func:`read_table`, refer to its + documentation for the available options, e.g. for reading DataFrame + indexes or applying filters. + +Returns +------- +pyarrow.Table Content of the file as a Table of Columns, including DataFrame - indexes as columns""", - _DNF_filter_doc, "") + indexes as columns +""" def write_table(table, where, row_group_size=None, version='2.6', diff --git a/python/pyarrow/tests/test_pandas.py b/python/pyarrow/tests/test_pandas.py index 1f09a9247e6b..6a03fc01e4f9 100644 --- a/python/pyarrow/tests/test_pandas.py +++ b/python/pyarrow/tests/test_pandas.py @@ -3004,6 +3004,24 @@ def test_zero_copy_failure_on_duration_with_nulls(self): arr = np.array([1, None], dtype='timedelta64[ns]') self.check_zero_copy_failure(pa.array(arr)) + def test_zero_copy_table_success(self): + # GH-39194: zero-copy conversion of a Table needs one block per + # column, which is enabled automatically for the DataFrame path + table = pa.table({'a': [0, 1, 2], 'b': [0.0, 1.0, 2.0]}) + result = table.to_pandas(zero_copy_only=True) + expected = pd.DataFrame({'a': [0, 1, 2], 'b': [0.0, 1.0, 2.0]}) + tm.assert_frame_equal(result, expected) + + def test_zero_copy_table_failure_when_copy_needed(self): + table = pa.table({'a': [0, 1, None]}) + with pytest.raises(pa.ArrowInvalid): + table.to_pandas(zero_copy_only=True) + + def test_zero_copy_table_failure_with_strings_to_categorical(self): + table = pa.table({'a': ['A', 'B', 'C']}) + with pytest.raises(pa.ArrowInvalid): + table.to_pandas(zero_copy_only=True, strings_to_categorical=True) + def _non_threaded_conversion(): df = _alltypes_example()