Skip to content
Open
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
1 change: 1 addition & 0 deletions docs/source/python/api/filesystems.rst
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ Interface
:toctree: ../generated/

FileInfo
FileInfoIterator
FileSelector
FileSystem

Expand Down
19 changes: 19 additions & 0 deletions python/pyarrow/_fs.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,25 @@ cdef class FileSelector(_Weakrefable):
cdef inline CFileSelector unwrap(self) nogil


cdef class FileInfoIterator(_Weakrefable):
cdef:
object iterator_owner
object iteration_lock
FileSelector selector
vector[CFileInfo] batch
size_t batch_index
c_bool started
c_bool finished
SharedPtrNoGIL[CFileInfoVectorIterator] iterator

@staticmethod
cdef wrap(object owner, FileSelector selector)

cdef _start(self)

cdef _close(self)


cdef class FileSystem(_Weakrefable):
cdef:
shared_ptr[CFileSystem] wrapped
Expand Down
134 changes: 134 additions & 0 deletions python/pyarrow/_fs.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ from pyarrow.util import _stringify_path

from abc import ABC, abstractmethod
from datetime import datetime, timezone
from threading import Lock
import os
import pathlib
import sys
Expand Down Expand Up @@ -408,6 +409,100 @@ cdef class FileSelector(_Weakrefable):
return f"<FileSelector base_dir={self.base_dir!r} recursive={self.recursive}>"


cdef class FileInfoIterator(_Weakrefable):
"""
An iterator over FileInfo objects produced by a file selector.

Create an iterator with ``FileSystem.get_file_info_iterator()``.

File discovery starts on the first ``next()`` call, not when the
iterator is created. Entries are fetched from the filesystem in
batches and yielded one at a time. Iteration releases its resources
on exhaustion or error. Call ``close()`` to release them when
stopping early. Concurrent calls to ``next()`` or ``close()`` on the
same iterator raise ``ValueError``.
"""

def __cinit__(self):
self.iteration_lock = Lock()
self.batch_index = 0
self.started = False
self.finished = False

def __init__(self):
raise TypeError(
"FileInfoIterator cannot be instantiated directly; "
"use FileSystem.get_file_info_iterator() instead")

@staticmethod
cdef wrap(object owner, FileSelector selector):
cdef FileInfoIterator self = \
FileInfoIterator.__new__(FileInfoIterator)
self.iterator_owner = owner
self.selector = selector
return self

def __iter__(self):
return self

def __next__(self):
cdef CFileInfo info
if not self.iteration_lock.acquire(blocking=False):
raise ValueError("iterator already executing")
try:
if self.finished:
raise StopIteration
try:
if not self.started:
self._start()
while self.batch_index == self.batch.size():
with nogil:
self.batch = GetResultValue(
self.iterator.get().Next())
self.batch_index = 0
if self.batch.empty():
raise StopIteration
info = self.batch[self.batch_index]
result = FileInfo.wrap(info)
self.batch_index += 1
return result
except BaseException:
self._close()
raise
finally:
self.iteration_lock.release()

def close(self):
"""Stop iteration and release the underlying C++ resources."""
if not self.iteration_lock.acquire(blocking=False):
raise ValueError("iterator already executing")
try:
self._close()
finally:
self.iteration_lock.release()

cdef _start(self):
cdef:
CFileSelector c_selector = self.selector.selector
shared_ptr[CFileSystem] filesystem = \
(<FileSystem> self.iterator_owner).wrapped
CFileInfoVectorIterator iterator
with nogil:
iterator = MakeFileInfoVectorIterator(filesystem, c_selector)
self.iterator = make_shared[CFileInfoVectorIterator](move(iterator))
self.started = True

cdef _close(self):
cdef vector[CFileInfo] empty_batch
with nogil:
self.iterator.reset()
self.batch.swap(empty_batch)
self.batch_index = 0
self.finished = True
self.iterator_owner = None
self.selector = None


cdef class FileSystem(_Weakrefable):
"""
Abstract file system API.
Expand Down Expand Up @@ -620,6 +715,45 @@ cdef class FileSystem(_Weakrefable):

return [FileInfo.wrap(info) for info in infos]

def get_file_info_iterator(self, FileSelector selector not None):
"""
Get file information from a selector as an iterator of FileInfo.

Unlike :meth:`get_file_info`, which returns a list once the whole
selection has been listed, this method returns an iterator that
yields ``FileInfo`` objects one at a time. File discovery starts
on the first ``next()`` call, and entries are fetched from the
filesystem in batches.

Whether discovery is actually incremental depends on the
filesystem. ``LocalFileSystem`` and ``S3FileSystem`` expose batches
as discovery progresses, allowing processing to overlap with listing.
Other filesystems, including ``GcsFileSystem``,
``AzureFileSystem``, ``HadoopFileSystem`` and ``PyFileSystem``
(which backs the fsspec integration), currently list the whole
selection on the first ``next()`` call and then yield it from
memory; for those, stopping early saves no listing work. In all
cases the entries yielded are the same as ``get_file_info``.

The order in which entries are yielded is not guaranteed.

Call :meth:`FileInfoIterator.close` to release resources when
stopping early; exhausting the iterator releases them
automatically. Filesystems that prefetch results may already have
started work that closing does not cancel.

Parameters
----------
selector : FileSelector
The selector describing the directory to list.

Returns
-------
FileInfoIterator
A closeable iterator yielding ``FileInfo`` objects.
"""
return FileInfoIterator.wrap(self, selector)

def create_dir(self, path, *, bint recursive=True):
"""
Create a directory and subdirectories.
Expand Down
1 change: 1 addition & 0 deletions python/pyarrow/fs.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
FileSelector,
FileType,
FileInfo,
FileInfoIterator,
FileSystem,
LocalFileSystem,
SubTreeFileSystem,
Expand Down
10 changes: 10 additions & 0 deletions python/pyarrow/includes/libarrow_fs.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,16 @@ from pyarrow.includes.common cimport *
from pyarrow.includes.libarrow cimport *
from pyarrow.includes.libarrow_python cimport CTimePoint

cdef extern from "arrow/python/filesystem_iterator.h" namespace "arrow::py::fs" nogil:
cdef cppclass CFileInfoVectorIterator \
"arrow::py::fs::FileInfoVectorIterator":
CResult[vector[CFileInfo]] Next()

CFileInfoVectorIterator MakeFileInfoVectorIterator(
const shared_ptr[CFileSystem]& filesystem,
const CFileSelector& selector)


cdef extern from "arrow/filesystem/api.h" namespace "arrow::fs" nogil:

ctypedef enum CFileType "arrow::fs::FileType":
Expand Down
56 changes: 56 additions & 0 deletions python/pyarrow/src/arrow/python/filesystem_iterator.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

#pragma once

#include <memory>
#include <utility>

#include "arrow/filesystem/filesystem.h"
#include "arrow/util/future.h"
#include "arrow/util/iterator.h"

namespace arrow::py::fs {

class FileInfoVectorIterator {
public:
FileInfoVectorIterator() = default;
explicit FileInfoVectorIterator(arrow::fs::FileInfoGenerator generator)
: generator_(std::move(generator)) {}

Result<arrow::fs::FileInfoVector> Next() {
if (!generator_) {
return IterationEnd<arrow::fs::FileInfoVector>();
}
auto next = generator_().result();
if (!next.ok() || IsIterationEnd(*next)) {
generator_ = nullptr;
}
return next;
}

private:
arrow::fs::FileInfoGenerator generator_;
};

inline FileInfoVectorIterator MakeFileInfoVectorIterator(
const std::shared_ptr<arrow::fs::FileSystem>& filesystem,
const arrow::fs::FileSelector& selector) {
return FileInfoVectorIterator(filesystem->GetFileInfoGenerator(selector));
}

} // namespace arrow::py::fs
Loading