Debian Codegraph @

Doc/library/importlib.resources.rst

raw
1 :mod:`!importlib.resources` -- Package resource reading, opening and access
2 ---------------------------------------------------------------------------
3
4 .. module:: importlib.resources
5 :synopsis: Package resource reading, opening, and access
6
7 **Source code:** :source:`Lib/importlib/resources/__init__.py`
8
9 --------------
10
11 .. versionadded:: 3.7
12
13 This module leverages Python's import system to provide access to *resources*
14 within *packages*.
15
16 "Resources" are file-like resources associated with a module or package in
17 Python. The resources may be contained directly in a package, within a
18 subdirectory contained in that package, or adjacent to modules outside a
19 package. Resources may be text or binary. As a result, a package's Python
20 module sources (.py), compilation artifacts (pycache), and installation
21 artifacts (like :func:`reserved filenames <os.path.isreserved>`
22 in directories) are technically de-facto resources of that package.
23 In practice, however, resources are primarily those non-Python artifacts
24 exposed specifically by the package author.
25
26 Resources can be opened or read in either binary or text mode.
27
28 Resources are roughly akin to files inside directories, though it's important
29 to keep in mind that this is just a metaphor. Resources and packages **do
30 not** have to exist as physical files and directories on the file system:
31 for example, a package and its resources can be imported from a zip file using
32 :py:mod:`zipimport`.
33
34 .. note::
35
36 This module provides functionality similar to `pkg_resources
37 <https://setuptools.readthedocs.io/en/latest/pkg_resources.html>`_ `Basic
38 Resource Access
39 <https://setuptools.readthedocs.io/en/latest/pkg_resources.html#basic-resource-access>`_
40 without the performance overhead of that package. This makes reading
41 resources included in packages easier, with more stable and consistent
42 semantics.
43
44 The standalone backport of this module provides more information
45 on `using importlib.resources
46 <https://importlib-resources.readthedocs.io/en/latest/using.html>`_ and
47 `migrating from pkg_resources to importlib.resources
48 <https://importlib-resources.readthedocs.io/en/latest/migration.html>`_.
49
50 :class:`Loaders <importlib.abc.Loader>` that wish to support resource reading should implement a
51 ``get_resource_reader(fullname)`` method as specified by
52 :class:`importlib.resources.abc.ResourceReader`.
53
54 .. class:: Anchor
55
56 Represents an anchor for resources, either a :class:`module object
57 <types.ModuleType>` or a module name as a string. Defined as
58 ``Union[str, ModuleType]``.
59
60 .. function:: files(anchor: Optional[Anchor] = None)
61
62 Returns a :class:`~importlib.resources.abc.Traversable` object
63 representing the resource container (think directory) and its resources
64 (think files). A Traversable may contain other containers (think
65 subdirectories).
66
67 *anchor* is an optional :class:`Anchor`. If the anchor is a
68 package, resources are resolved from that package. If a module,
69 resources are resolved adjacent to that module (in the same package
70 or the package root). If the anchor is omitted, the caller's module
71 is used.
72
73 .. versionadded:: 3.9
74
75 .. versionchanged:: 3.12
76 *package* parameter was renamed to *anchor*. *anchor* can now
77 be a non-package module and if omitted will default to the caller's
78 module. *package* is still accepted for compatibility but will raise
79 a :exc:`DeprecationWarning`. Consider passing the anchor positionally or
80 using ``importlib_resources >= 5.10`` for a compatible interface
81 on older Pythons.
82
83 .. function:: as_file(traversable)
84
85 Given a :class:`~importlib.resources.abc.Traversable` object representing
86 a file or directory, typically from :func:`importlib.resources.files`,
87 return a context manager for use in a :keyword:`with` statement.
88 The context manager provides a :class:`pathlib.Path` object.
89
90 Exiting the context manager cleans up any temporary file or directory
91 created when the resource was extracted from e.g. a zip file.
92
93 Use ``as_file`` when the Traversable methods
94 (``read_text``, etc) are insufficient and an actual file or directory on
95 the file system is required.
96
97 .. versionadded:: 3.9
98
99 .. versionchanged:: 3.12
100 Added support for *traversable* representing a directory.
101
102
103 .. _importlib_resources_functional:
104
105 Functional API
106 ^^^^^^^^^^^^^^
107
108 A set of simplified, backwards-compatible helpers is available.
109 These allow common operations in a single function call.
110
111 For all the following functions:
112
113 - *anchor* is an :class:`~importlib.resources.Anchor`,
114 as in :func:`~importlib.resources.files`.
115 Unlike in ``files``, it may not be omitted.
116
117 - *path_names* are components of a resource's path name, relative to
118 the anchor.
119 For example, to get the text of resource named ``info.txt``, use::
120
121 importlib.resources.read_text(my_module, "info.txt")
122
123 Like :meth:`Traversable.joinpath <importlib.resources.abc.Traversable>`,
124 The individual components should use forward slashes (``/``)
125 as path separators.
126 For example, the following are equivalent::
127
128 importlib.resources.read_binary(my_module, "pics/painting.png")
129 importlib.resources.read_binary(my_module, "pics", "painting.png")
130
131 For backward compatibility reasons, functions that read text require
132 an explicit *encoding* argument if multiple *path_names* are given.
133 For example, to get the text of ``info/chapter1.txt``, use::
134
135 importlib.resources.read_text(my_module, "info", "chapter1.txt",
136 encoding='utf-8')
137
138 .. function:: open_binary(anchor, *path_names)
139
140 Open the named resource for binary reading.
141
142 See :ref:`the introduction <importlib_resources_functional>` for
143 details on *anchor* and *path_names*.
144
145 This function returns a :class:`~typing.BinaryIO` object,
146 that is, a binary stream open for reading.
147
148 This function is roughly equivalent to::
149
150 files(anchor).joinpath(*path_names).open('rb')
151
152 .. versionchanged:: 3.13
153 Multiple *path_names* are accepted.
154
155
156 .. function:: open_text(anchor, *path_names, encoding='utf-8', errors='strict')
157
158 Open the named resource for text reading.
159 By default, the contents are read as strict UTF-8.
160
161 See :ref:`the introduction <importlib_resources_functional>` for
162 details on *anchor* and *path_names*.
163 *encoding* and *errors* have the same meaning as in built-in :func:`open`.
164
165 For backward compatibility reasons, the *encoding* argument must be given
166 explicitly if there are multiple *path_names*.
167 This limitation is scheduled to be removed in Python 3.15.
168
169 This function returns a :class:`~typing.TextIO` object,
170 that is, a text stream open for reading.
171
172 This function is roughly equivalent to::
173
174 files(anchor).joinpath(*path_names).open('r', encoding=encoding)
175
176 .. versionchanged:: 3.13
177 Multiple *path_names* are accepted.
178 *encoding* and *errors* must be given as keyword arguments.
179
180
181 .. function:: read_binary(anchor, *path_names)
182
183 Read and return the contents of the named resource as :class:`bytes`.
184
185 See :ref:`the introduction <importlib_resources_functional>` for
186 details on *anchor* and *path_names*.
187
188 This function is roughly equivalent to::
189
190 files(anchor).joinpath(*path_names).read_bytes()
191
192 .. versionchanged:: 3.13
193 Multiple *path_names* are accepted.
194
195
196 .. function:: read_text(anchor, *path_names, encoding='utf-8', errors='strict')
197
198 Read and return the contents of the named resource as :class:`str`.
199 By default, the contents are read as strict UTF-8.
200
201 See :ref:`the introduction <importlib_resources_functional>` for
202 details on *anchor* and *path_names*.
203 *encoding* and *errors* have the same meaning as in built-in :func:`open`.
204
205 For backward compatibility reasons, the *encoding* argument must be given
206 explicitly if there are multiple *path_names*.
207 This limitation is scheduled to be removed in Python 3.15.
208
209 This function is roughly equivalent to::
210
211 files(anchor).joinpath(*path_names).read_text(encoding=encoding)
212
213 .. versionchanged:: 3.13
214 Multiple *path_names* are accepted.
215 *encoding* and *errors* must be given as keyword arguments.
216
217
218 .. function:: path(anchor, *path_names)
219
220 Provides the path to the *resource* as an actual file system path. This
221 function returns a context manager for use in a :keyword:`with` statement.
222 The context manager provides a :class:`pathlib.Path` object.
223
224 Exiting the context manager cleans up any temporary files created, e.g.
225 when the resource needs to be extracted from a zip file.
226
227 For example, the :meth:`~pathlib.Path.stat` method requires
228 an actual file system path; it can be used like this::
229
230 with importlib.resources.path(anchor, "resource.txt") as fspath:
231 result = fspath.stat()
232
233 See :ref:`the introduction <importlib_resources_functional>` for
234 details on *anchor* and *path_names*.
235
236 This function is roughly equivalent to::
237
238 as_file(files(anchor).joinpath(*path_names))
239
240 .. versionchanged:: 3.13
241 Multiple *path_names* are accepted.
242 *encoding* and *errors* must be given as keyword arguments.
243
244
245 .. function:: is_resource(anchor, *path_names)
246
247 Return ``True`` if the named resource exists, otherwise ``False``.
248 This function does not consider directories to be resources.
249
250 See :ref:`the introduction <importlib_resources_functional>` for
251 details on *anchor* and *path_names*.
252
253 This function is roughly equivalent to::
254
255 files(anchor).joinpath(*path_names).is_file()
256
257 .. versionchanged:: 3.13
258 Multiple *path_names* are accepted.
259
260
261 .. function:: contents(anchor, *path_names)
262
263 Return an iterable over the named items within the package or path.
264 The iterable returns names of resources (e.g. files) and non-resources
265 (e.g. directories) as :class:`str`.
266 The iterable does not recurse into subdirectories.
267
268 See :ref:`the introduction <importlib_resources_functional>` for
269 details on *anchor* and *path_names*.
270
271 This function is roughly equivalent to::
272
273 for resource in files(anchor).joinpath(*path_names).iterdir():
274 yield resource.name
275
276 .. deprecated:: 3.11
277 Prefer ``iterdir()`` as above, which offers more control over the
278 results and richer functionality.