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