|
| 1 | +"""Data file retrieval |
| 2 | +
|
| 3 | +.. autofunction:: load |
| 4 | +
|
| 5 | +.. automethod:: load.readable |
| 6 | +
|
| 7 | +.. automethod:: load.as_path |
| 8 | +
|
| 9 | +.. automethod:: load.cached |
| 10 | +
|
| 11 | +.. autoclass:: Loader |
| 12 | +""" |
| 13 | + |
| 14 | +from __future__ import annotations |
| 15 | + |
1 | 16 | import atexit
|
2 |
| -from contextlib import ExitStack |
| 17 | +import os |
| 18 | +from contextlib import AbstractContextManager, ExitStack |
| 19 | +from functools import cached_property |
3 | 20 | from pathlib import Path
|
| 21 | +from types import ModuleType |
| 22 | +from typing import Union |
4 | 23 |
|
5 | 24 | try:
|
6 | 25 | from functools import cache
|
|
10 | 29 | try: # Prefer backport to leave consistency to dependency spec
|
11 | 30 | from importlib_resources import as_file, files
|
12 | 31 | except ImportError:
|
13 |
| - from importlib.resources import as_file, files |
| 32 | + from importlib.resources import as_file, files # type: ignore |
| 33 | + |
| 34 | +try: # Prefer stdlib so Sphinx can link to authoritative documentation |
| 35 | + from importlib.resources.abc import Traversable |
| 36 | +except ImportError: |
| 37 | + from importlib_resources.abc import Traversable |
| 38 | + |
| 39 | +__all__ = ["load"] |
| 40 | + |
| 41 | + |
| 42 | +class Loader: |
| 43 | + """A loader for package files relative to a module |
| 44 | +
|
| 45 | + This class wraps :mod:`importlib.resources` to provide a getter |
| 46 | + function with an interpreter-lifetime scope. For typical packages |
| 47 | + it simply passes through filesystem paths as :class:`~pathlib.Path` |
| 48 | + objects. For zipped distributions, it will unpack the files into |
| 49 | + a temporary directory that is cleaned up on interpreter exit. |
| 50 | +
|
| 51 | + This loader accepts a fully-qualified module name or a module |
| 52 | + object. |
| 53 | +
|
| 54 | + Expected usage:: |
| 55 | +
|
| 56 | + '''Data package |
| 57 | +
|
| 58 | + .. autofunction:: load_data |
| 59 | +
|
| 60 | + .. automethod:: load_data.readable |
| 61 | +
|
| 62 | + .. automethod:: load_data.as_path |
| 63 | +
|
| 64 | + .. automethod:: load_data.cached |
| 65 | + ''' |
| 66 | +
|
| 67 | + from nibabies.data import Loader |
| 68 | +
|
| 69 | + load_data = Loader(__package__) |
| 70 | +
|
| 71 | + :class:`~Loader` objects implement the :func:`callable` interface |
| 72 | + and generate a docstring, and are intended to be treated and documented |
| 73 | + as functions. |
| 74 | +
|
| 75 | + For greater flexibility and improved readability over the ``importlib.resources`` |
| 76 | + interface, explicit methods are provided to access resources. |
| 77 | +
|
| 78 | + +---------------+----------------+------------------+ |
| 79 | + | On-filesystem | Lifetime | Method | |
| 80 | + +---------------+----------------+------------------+ |
| 81 | + | `True` | Interpreter | :meth:`cached` | |
| 82 | + +---------------+----------------+------------------+ |
| 83 | + | `True` | `with` context | :meth:`as_path` | |
| 84 | + +---------------+----------------+------------------+ |
| 85 | + | `False` | n/a | :meth:`readable` | |
| 86 | + +---------------+----------------+------------------+ |
| 87 | +
|
| 88 | + It is also possible to use ``Loader`` directly:: |
| 89 | +
|
| 90 | + from nibabies.data import Loader |
| 91 | +
|
| 92 | + Loader(other_package).readable('data/resource.ext').read_text() |
| 93 | +
|
| 94 | + with Loader(other_package).as_path('data') as pkgdata: |
| 95 | + # Call function that requires full Path implementation |
| 96 | + func(pkgdata) |
| 97 | +
|
| 98 | + # contrast to |
| 99 | +
|
| 100 | + from importlib_resources import files, as_file |
| 101 | +
|
| 102 | + files(other_package).joinpath('data/resource.ext').read_text() |
| 103 | +
|
| 104 | + with as_file(files(other_package) / 'data') as pkgdata: |
| 105 | + func(pkgdata) |
| 106 | +
|
| 107 | + .. automethod:: readable |
| 108 | +
|
| 109 | + .. automethod:: as_path |
| 110 | +
|
| 111 | + .. automethod:: cached |
| 112 | + """ |
| 113 | + |
| 114 | + def __init__(self, anchor: Union[str, ModuleType]): |
| 115 | + self._anchor = anchor |
| 116 | + self.files = files(anchor) |
| 117 | + self.exit_stack = ExitStack() |
| 118 | + atexit.register(self.exit_stack.close) |
| 119 | + # Allow class to have a different docstring from instances |
| 120 | + self.__doc__ = self._doc |
| 121 | + |
| 122 | + @cached_property |
| 123 | + def _doc(self): |
| 124 | + """Construct docstring for instances |
| 125 | +
|
| 126 | + Lists the public top-level paths inside the location, where |
| 127 | + non-public means has a `.` or `_` prefix or is a 'tests' |
| 128 | + directory. |
| 129 | + """ |
| 130 | + top_level = sorted( |
| 131 | + os.path.relpath(p, self.files) + "/"[: p.is_dir()] |
| 132 | + for p in self.files.iterdir() |
| 133 | + if p.name[0] not in (".", "_") and p.name != "tests" |
| 134 | + ) |
| 135 | + doclines = [ |
| 136 | + f"Load package files relative to ``{self._anchor}``.", |
| 137 | + "", |
| 138 | + "This package contains the following (top-level) files/directories:", |
| 139 | + "", |
| 140 | + *(f"* ``{path}``" for path in top_level), |
| 141 | + ] |
| 142 | + |
| 143 | + return "\n".join(doclines) |
| 144 | + |
| 145 | + def readable(self, *segments) -> Traversable: |
| 146 | + """Provide read access to a resource through a Path-like interface. |
| 147 | +
|
| 148 | + This file may or may not exist on the filesystem, and may be |
| 149 | + efficiently used for read operations, including directory traversal. |
| 150 | +
|
| 151 | + This result is not cached or copied to the filesystem in cases where |
| 152 | + that would be necessary. |
| 153 | + """ |
| 154 | + return self.files.joinpath(*segments) |
| 155 | + |
| 156 | + def as_path(self, *segments) -> AbstractContextManager[Path]: |
| 157 | + """Ensure data is available as a :class:`~pathlib.Path`. |
| 158 | +
|
| 159 | + This method generates a context manager that yields a Path when |
| 160 | + entered. |
| 161 | +
|
| 162 | + This result is not cached, and any temporary files that are created |
| 163 | + are deleted when the context is exited. |
| 164 | + """ |
| 165 | + return as_file(self.files.joinpath(*segments)) |
| 166 | + |
| 167 | + @cache |
| 168 | + def cached(self, *segments) -> Path: |
| 169 | + """Ensure data is available as a :class:`~pathlib.Path`. |
14 | 170 |
|
15 |
| -__all__ = ["load_resource"] |
| 171 | + Any temporary files that are created remain available throughout |
| 172 | + the duration of the program, and are deleted when Python exits. |
16 | 173 |
|
17 |
| -exit_stack = ExitStack() |
18 |
| -atexit.register(exit_stack.close) |
| 174 | + Results are cached so that multiple calls do not unpack the same |
| 175 | + data multiple times, but the cache is sensitive to the specific |
| 176 | + argument(s) passed. |
| 177 | + """ |
| 178 | + return self.exit_stack.enter_context(as_file(self.files.joinpath(*segments))) |
19 | 179 |
|
20 |
| -path = files(__package__) |
| 180 | + __call__ = cached |
21 | 181 |
|
22 | 182 |
|
23 |
| -@cache |
24 |
| -def load_resource(fname: str) -> Path: |
25 |
| - return exit_stack.enter_context(as_file(path.joinpath(fname))) |
| 183 | +load = Loader(__package__) |
0 commit comments