1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
|
<span id="importlib-the-implementation-of-import"></span><h1>importlib — The implementation of import</h1> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.1.</span></p> </div> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/importlib/__init__.py">Lib/importlib/__init__.py</a></p> <section id="introduction"> <h2>Introduction</h2> <p>The purpose of the <a class="reference internal" href="#module-importlib" title="importlib: The implementation of the import machinery."><code>importlib</code></a> package is three-fold.</p> <p>One is to provide the implementation of the <a class="reference internal" href="../reference/simple_stmts#import"><code>import</code></a> statement (and thus, by extension, the <a class="reference internal" href="functions#import__" title="__import__"><code>__import__()</code></a> function) in Python source code. This provides an implementation of <code>import</code> which is portable to any Python interpreter. This also provides an implementation which is easier to comprehend than one implemented in a programming language other than Python.</p> <p>Two, the components to implement <a class="reference internal" href="../reference/simple_stmts#import"><code>import</code></a> are exposed in this package, making it easier for users to create their own custom objects (known generically as an <a class="reference internal" href="../glossary#term-importer"><span class="xref std std-term">importer</span></a>) to participate in the import process.</p> <p>Three, the package contains modules exposing additional functionality for managing aspects of Python packages:</p> <ul class="simple"> <li>
<a class="reference internal" href="importlib.metadata#module-importlib.metadata" title="importlib.metadata: Accessing package metadata"><code>importlib.metadata</code></a> presents access to metadata from third-party distributions.</li> <li>
<a class="reference internal" href="importlib.resources#module-importlib.resources" title="importlib.resources: Package resource reading, opening, and access"><code>importlib.resources</code></a> provides routines for accessing non-code “resources” from Python packages.</li> </ul> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt><a class="reference internal" href="../reference/simple_stmts#import"><span class="std std-ref">The import statement</span></a></dt>
<dd>
<p>The language reference for the <a class="reference internal" href="../reference/simple_stmts#import"><code>import</code></a> statement.</p> </dd> <dt><a class="reference external" href="https://www.python.org/doc/essays/packages/">Packages specification</a></dt>
<dd>
<p>Original specification of packages. Some semantics have changed since the writing of this document (e.g. redirecting based on <code>None</code> in <a class="reference internal" href="sys#sys.modules" title="sys.modules"><code>sys.modules</code></a>).</p> </dd> <dt>
<code>The __import__() function</code> </dt>
<dd>
<p>The <a class="reference internal" href="../reference/simple_stmts#import"><code>import</code></a> statement is syntactic sugar for this function.</p> </dd> <dt><a class="reference internal" href="sys_path_init#sys-path-init"><span class="std std-ref">The initialization of the sys.path module search path</span></a></dt>
<dd>
<p>The initialization of <a class="reference internal" href="sys#sys.path" title="sys.path"><code>sys.path</code></a>.</p> </dd> <dt>
<span class="target" id="index-0"></span><a class="pep reference external" href="https://peps.python.org/pep-0235/"><strong>PEP 235</strong></a>
</dt>
<dd>
<p>Import on Case-Insensitive Platforms</p> </dd> <dt>
<span class="target" id="index-1"></span><a class="pep reference external" href="https://peps.python.org/pep-0263/"><strong>PEP 263</strong></a>
</dt>
<dd>
<p>Defining Python Source Code Encodings</p> </dd> <dt>
<span class="target" id="index-2"></span><a class="pep reference external" href="https://peps.python.org/pep-0302/"><strong>PEP 302</strong></a>
</dt>
<dd>
<p>New Import Hooks</p> </dd> <dt>
<span class="target" id="index-3"></span><a class="pep reference external" href="https://peps.python.org/pep-0328/"><strong>PEP 328</strong></a>
</dt>
<dd>
<p>Imports: Multi-Line and Absolute/Relative</p> </dd> <dt>
<span class="target" id="index-4"></span><a class="pep reference external" href="https://peps.python.org/pep-0366/"><strong>PEP 366</strong></a>
</dt>
<dd>
<p>Main module explicit relative imports</p> </dd> <dt>
<span class="target" id="index-5"></span><a class="pep reference external" href="https://peps.python.org/pep-0420/"><strong>PEP 420</strong></a>
</dt>
<dd>
<p>Implicit namespace packages</p> </dd> <dt>
<span class="target" id="index-6"></span><a class="pep reference external" href="https://peps.python.org/pep-0451/"><strong>PEP 451</strong></a>
</dt>
<dd>
<p>A ModuleSpec Type for the Import System</p> </dd> <dt>
<span class="target" id="index-7"></span><a class="pep reference external" href="https://peps.python.org/pep-0488/"><strong>PEP 488</strong></a>
</dt>
<dd>
<p>Elimination of PYO files</p> </dd> <dt>
<span class="target" id="index-8"></span><a class="pep reference external" href="https://peps.python.org/pep-0489/"><strong>PEP 489</strong></a>
</dt>
<dd>
<p>Multi-phase extension module initialization</p> </dd> <dt>
<span class="target" id="index-9"></span><a class="pep reference external" href="https://peps.python.org/pep-0552/"><strong>PEP 552</strong></a>
</dt>
<dd>
<p>Deterministic pycs</p> </dd> <dt>
<span class="target" id="index-10"></span><a class="pep reference external" href="https://peps.python.org/pep-3120/"><strong>PEP 3120</strong></a>
</dt>
<dd>
<p>Using UTF-8 as the Default Source Encoding</p> </dd> <dt>
<span class="target" id="index-11"></span><a class="pep reference external" href="https://peps.python.org/pep-3147/"><strong>PEP 3147</strong></a>
</dt>
<dd>
<p>PYC Repository Directories</p> </dd> </dl> </div> </section> <section id="functions"> <h2>Functions</h2> <dl class="py function"> <dt class="sig sig-object py" id="importlib.__import__">
<code>importlib.__import__(name, globals=None, locals=None, fromlist=(), level=0)</code> </dt> <dd>
<p>An implementation of the built-in <a class="reference internal" href="functions#import__" title="__import__"><code>__import__()</code></a> function.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Programmatic importing of modules should use <a class="reference internal" href="#importlib.import_module" title="importlib.import_module"><code>import_module()</code></a> instead of this function.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="importlib.import_module">
<code>importlib.import_module(name, package=None)</code> </dt> <dd>
<p>Import a module. The <em>name</em> argument specifies what module to import in absolute or relative terms (e.g. either <code>pkg.mod</code> or <code>..mod</code>). If the name is specified in relative terms, then the <em>package</em> argument must be set to the name of the package which is to act as the anchor for resolving the package name (e.g. <code>import_module('..mod', 'pkg.subpkg')</code> will import <code>pkg.mod</code>).</p> <p>The <a class="reference internal" href="#importlib.import_module" title="importlib.import_module"><code>import_module()</code></a> function acts as a simplifying wrapper around <a class="reference internal" href="#importlib.__import__" title="importlib.__import__"><code>importlib.__import__()</code></a>. This means all semantics of the function are derived from <a class="reference internal" href="#importlib.__import__" title="importlib.__import__"><code>importlib.__import__()</code></a>. The most important difference between these two functions is that <a class="reference internal" href="#importlib.import_module" title="importlib.import_module"><code>import_module()</code></a> returns the specified package or module (e.g. <code>pkg.mod</code>), while <a class="reference internal" href="functions#import__" title="__import__"><code>__import__()</code></a> returns the top-level package or module (e.g. <code>pkg</code>).</p> <p>If you are dynamically importing a module that was created since the interpreter began execution (e.g., created a Python source file), you may need to call <a class="reference internal" href="#importlib.invalidate_caches" title="importlib.invalidate_caches"><code>invalidate_caches()</code></a> in order for the new module to be noticed by the import system.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>Parent packages are automatically imported.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="importlib.invalidate_caches">
<code>importlib.invalidate_caches()</code> </dt> <dd>
<p>Invalidate the internal caches of finders stored at <a class="reference internal" href="sys#sys.meta_path" title="sys.meta_path"><code>sys.meta_path</code></a>. If a finder implements <code>invalidate_caches()</code> then it will be called to perform the invalidation. This function should be called if any modules are created/installed while your program is running to guarantee all finders will notice the new module’s existence.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span>Namespace packages created/installed in a different <a class="reference internal" href="sys#sys.path" title="sys.path"><code>sys.path</code></a> location after the same namespace was already imported are noticed.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="importlib.reload">
<code>importlib.reload(module)</code> </dt> <dd>
<p>Reload a previously imported <em>module</em>. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter. The return value is the module object (which can be different if re-importing causes a different object to be placed in <a class="reference internal" href="sys#sys.modules" title="sys.modules"><code>sys.modules</code></a>).</p> <p>When <a class="reference internal" href="#importlib.reload" title="importlib.reload"><code>reload()</code></a> is executed:</p> <ul class="simple"> <li>Python module’s code is recompiled and the module-level code re-executed, defining a new set of objects which are bound to names in the module’s dictionary by reusing the <a class="reference internal" href="../glossary#term-loader"><span class="xref std std-term">loader</span></a> which originally loaded the module. The <code>init</code> function of extension modules is not called a second time.</li> <li>As with all other objects in Python the old objects are only reclaimed after their reference counts drop to zero.</li> <li>The names in the module namespace are updated to point to any new or changed objects.</li> <li>Other references to the old objects (such as names external to the module) are not rebound to refer to the new objects and must be updated in each namespace where they occur if that is desired.</li> </ul> <p>There are a number of other caveats:</p> <p>When a module is reloaded, its dictionary (containing the module’s global variables) is retained. Redefinitions of names will override the old definitions, so this is generally not a problem. If the new version of a module does not define a name that was defined by the old version, the old definition remains. This feature can be used to the module’s advantage if it maintains a global table or cache of objects — with a <a class="reference internal" href="../reference/compound_stmts#try"><code>try</code></a> statement it can test for the table’s presence and skip its initialization if desired:</p> <pre data-language="python">try:
cache
except NameError:
cache = {}
</pre> <p>It is generally not very useful to reload built-in or dynamically loaded modules. Reloading <a class="reference internal" href="sys#module-sys" title="sys: Access system-specific parameters and functions."><code>sys</code></a>, <a class="reference internal" href="__main__#module-__main__" title="__main__: The environment where top-level code is run. Covers command-line interfaces, import-time behavior, and ``__name__ == '__main__'``."><code>__main__</code></a>, <a class="reference internal" href="builtins#module-builtins" title="builtins: The module that provides the built-in namespace."><code>builtins</code></a> and other key modules is not recommended. In many cases extension modules are not designed to be initialized more than once, and may fail in arbitrary ways when reloaded.</p> <p>If a module imports objects from another module using <a class="reference internal" href="../reference/simple_stmts#from"><code>from</code></a> … <a class="reference internal" href="../reference/simple_stmts#import"><code>import</code></a> …, calling <a class="reference internal" href="#importlib.reload" title="importlib.reload"><code>reload()</code></a> for the other module does not redefine the objects imported from it — one way around this is to re-execute the <code>from</code> statement, another is to use <code>import</code> and qualified names (<em>module.name</em>) instead.</p> <p>If a module instantiates instances of a class, reloading the module that defines the class does not affect the method definitions of the instances — they continue to use the old class definition. The same is true for derived classes.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span><a class="reference internal" href="exceptions#ModuleNotFoundError" title="ModuleNotFoundError"><code>ModuleNotFoundError</code></a> is raised when the module being reloaded lacks a <a class="reference internal" href="#importlib.machinery.ModuleSpec" title="importlib.machinery.ModuleSpec"><code>ModuleSpec</code></a>.</p> </div> </dd>
</dl> </section> <section id="module-importlib.abc"> <span id="importlib-abc-abstract-base-classes-related-to-import"></span><h2>importlib.abc – Abstract base classes related to import</h2> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/importlib/abc.py">Lib/importlib/abc.py</a></p> <p>The <a class="reference internal" href="#module-importlib.abc" title="importlib.abc: Abstract base classes related to import"><code>importlib.abc</code></a> module contains all of the core abstract base classes used by <a class="reference internal" href="../reference/simple_stmts#import"><code>import</code></a>. Some subclasses of the core abstract base classes are also provided to help in implementing the core ABCs.</p> <p>ABC hierarchy:</p> <pre data-language="python">object
+-- MetaPathFinder
+-- PathEntryFinder
+-- Loader
+-- ResourceLoader --------+
+-- InspectLoader |
+-- ExecutionLoader --+
+-- FileLoader
+-- SourceLoader
</pre> <dl class="py class"> <dt class="sig sig-object py" id="importlib.abc.MetaPathFinder">
<code>class importlib.abc.MetaPathFinder</code> </dt> <dd>
<p>An abstract base class representing a <a class="reference internal" href="../glossary#term-meta-path-finder"><span class="xref std std-term">meta path finder</span></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span>No longer a subclass of <code>Finder</code>.</p> </div> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.MetaPathFinder.find_spec">
<code>find_spec(fullname, path, target=None)</code> </dt> <dd>
<p>An abstract method for finding a <a class="reference internal" href="../glossary#term-module-spec"><span class="xref std std-term">spec</span></a> for the specified module. If this is a top-level import, <em>path</em> will be <code>None</code>. Otherwise, this is a search for a subpackage or module and <em>path</em> will be the value of <a class="reference internal" href="../reference/import#path__" title="__path__"><code>__path__</code></a> from the parent package. If a spec cannot be found, <code>None</code> is returned. When passed in, <code>target</code> is a module object that the finder may use to make a more educated guess about what spec to return. <a class="reference internal" href="#importlib.util.spec_from_loader" title="importlib.util.spec_from_loader"><code>importlib.util.spec_from_loader()</code></a> may be useful for implementing concrete <code>MetaPathFinders</code>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.MetaPathFinder.invalidate_caches">
<code>invalidate_caches()</code> </dt> <dd>
<p>An optional method which, when called, should invalidate any internal cache used by the finder. Used by <a class="reference internal" href="#importlib.invalidate_caches" title="importlib.invalidate_caches"><code>importlib.invalidate_caches()</code></a> when invalidating the caches of all finders on <a class="reference internal" href="sys#sys.meta_path" title="sys.meta_path"><code>sys.meta_path</code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>Returns <code>None</code> when called instead of <code>NotImplemented</code>.</p> </div> </dd>
</dl> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="importlib.abc.PathEntryFinder">
<code>class importlib.abc.PathEntryFinder</code> </dt> <dd>
<p>An abstract base class representing a <a class="reference internal" href="../glossary#term-path-entry-finder"><span class="xref std std-term">path entry finder</span></a>. Though it bears some similarities to <a class="reference internal" href="#importlib.abc.MetaPathFinder" title="importlib.abc.MetaPathFinder"><code>MetaPathFinder</code></a>, <code>PathEntryFinder</code> is meant for use only within the path-based import subsystem provided by <a class="reference internal" href="#importlib.machinery.PathFinder" title="importlib.machinery.PathFinder"><code>importlib.machinery.PathFinder</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span>No longer a subclass of <code>Finder</code>.</p> </div> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.PathEntryFinder.find_spec">
<code>find_spec(fullname, target=None)</code> </dt> <dd>
<p>An abstract method for finding a <a class="reference internal" href="../glossary#term-module-spec"><span class="xref std std-term">spec</span></a> for the specified module. The finder will search for the module only within the <a class="reference internal" href="../glossary#term-path-entry"><span class="xref std std-term">path entry</span></a> to which it is assigned. If a spec cannot be found, <code>None</code> is returned. When passed in, <code>target</code> is a module object that the finder may use to make a more educated guess about what spec to return. <a class="reference internal" href="#importlib.util.spec_from_loader" title="importlib.util.spec_from_loader"><code>importlib.util.spec_from_loader()</code></a> may be useful for implementing concrete <code>PathEntryFinders</code>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.PathEntryFinder.invalidate_caches">
<code>invalidate_caches()</code> </dt> <dd>
<p>An optional method which, when called, should invalidate any internal cache used by the finder. Used by <a class="reference internal" href="#importlib.machinery.PathFinder.invalidate_caches" title="importlib.machinery.PathFinder.invalidate_caches"><code>importlib.machinery.PathFinder.invalidate_caches()</code></a> when invalidating the caches of all cached finders.</p> </dd>
</dl> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="importlib.abc.Loader">
<code>class importlib.abc.Loader</code> </dt> <dd>
<p>An abstract base class for a <a class="reference internal" href="../glossary#term-loader"><span class="xref std std-term">loader</span></a>. See <span class="target" id="index-12"></span><a class="pep reference external" href="https://peps.python.org/pep-0302/"><strong>PEP 302</strong></a> for the exact definition for a loader.</p> <p>Loaders that wish to support resource reading should implement a <code>get_resource_reader()</code> method as specified by <a class="reference internal" href="importlib.resources.abc#importlib.resources.abc.ResourceReader" title="importlib.resources.abc.ResourceReader"><code>importlib.resources.abc.ResourceReader</code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>Introduced the optional <code>get_resource_reader()</code> method.</p> </div> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.Loader.create_module">
<code>create_module(spec)</code> </dt> <dd>
<p>A method that returns the module object to use when importing a module. This method may return <code>None</code>, indicating that default module creation semantics should take place.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>This method is no longer optional when <a class="reference internal" href="#importlib.abc.Loader.exec_module" title="importlib.abc.Loader.exec_module"><code>exec_module()</code></a> is defined.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.Loader.exec_module">
<code>exec_module(module)</code> </dt> <dd>
<p>An abstract method that executes the module in its own namespace when a module is imported or reloaded. The module should already be initialized when <a class="reference internal" href="#importlib.abc.Loader.exec_module" title="importlib.abc.Loader.exec_module"><code>exec_module()</code></a> is called. When this method exists, <a class="reference internal" href="#importlib.abc.Loader.create_module" title="importlib.abc.Loader.create_module"><code>create_module()</code></a> must be defined.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span><a class="reference internal" href="#importlib.abc.Loader.create_module" title="importlib.abc.Loader.create_module"><code>create_module()</code></a> must also be defined.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.Loader.load_module">
<code>load_module(fullname)</code> </dt> <dd>
<p>A legacy method for loading a module. If the module cannot be loaded, <a class="reference internal" href="exceptions#ImportError" title="ImportError"><code>ImportError</code></a> is raised, otherwise the loaded module is returned.</p> <p>If the requested module already exists in <a class="reference internal" href="sys#sys.modules" title="sys.modules"><code>sys.modules</code></a>, that module should be used and reloaded. Otherwise the loader should create a new module and insert it into <a class="reference internal" href="sys#sys.modules" title="sys.modules"><code>sys.modules</code></a> before any loading begins, to prevent recursion from the import. If the loader inserted a module and the load fails, it must be removed by the loader from <a class="reference internal" href="sys#sys.modules" title="sys.modules"><code>sys.modules</code></a>; modules already in <a class="reference internal" href="sys#sys.modules" title="sys.modules"><code>sys.modules</code></a> before the loader began execution should be left alone.</p> <p>The loader should set several attributes on the module (note that some of these attributes can change when a module is reloaded):</p> <ul class="simple"> <li>
<dl class="simple"> <dt>
<code></code> <a class="reference internal" href="../reference/import#name__" title="__name__"><code>__name__</code></a>
</dt>
<dd>
<p>The module’s fully qualified name. It is <code>'__main__'</code> for an executed module.</p> </dd> </dl> </li> <li>
<dl class="simple"> <dt>
<code></code> <a class="reference internal" href="../reference/import#file__" title="__file__"><code>__file__</code></a>
</dt>
<dd>
<p>The location the <a class="reference internal" href="../glossary#term-loader"><span class="xref std std-term">loader</span></a> used to load the module. For example, for modules loaded from a .py file this is the filename. It is not set on all modules (e.g. built-in modules).</p> </dd> </dl> </li> <li>
<dl class="simple"> <dt>
<code></code> <a class="reference internal" href="../reference/import#cached__" title="__cached__"><code>__cached__</code></a>
</dt>
<dd>
<p>The filename of a compiled version of the module’s code. It is not set on all modules (e.g. built-in modules).</p> </dd> </dl> </li> <li>
<dl class="simple"> <dt>
<code></code> <a class="reference internal" href="../reference/import#path__" title="__path__"><code>__path__</code></a>
</dt>
<dd>
<p>The list of locations where the package’s submodules will be found. Most of the time this is a single directory. The import system passes this attribute to <code>__import__()</code> and to finders in the same way as <a class="reference internal" href="sys#sys.path" title="sys.path"><code>sys.path</code></a> but just for the package. It is not set on non-package modules so it can be used as an indicator that the module is a package.</p> </dd> </dl> </li> <li>
<dl class="simple"> <dt>
<code></code> <a class="reference internal" href="../reference/import#package__" title="__package__"><code>__package__</code></a>
</dt>
<dd>
<p>The fully qualified name of the package the module is in (or the empty string for a top-level module). If the module is a package then this is the same as <a class="reference internal" href="../reference/import#name__" title="__name__"><code>__name__</code></a>.</p> </dd> </dl> </li> <li>
<dl class="simple"> <dt>
<code></code> <a class="reference internal" href="../reference/import#loader__" title="__loader__"><code>__loader__</code></a>
</dt>
<dd>
<p>The <a class="reference internal" href="../glossary#term-loader"><span class="xref std std-term">loader</span></a> used to load the module.</p> </dd> </dl> </li> </ul> <p>When <a class="reference internal" href="#importlib.abc.Loader.exec_module" title="importlib.abc.Loader.exec_module"><code>exec_module()</code></a> is available then backwards-compatible functionality is provided.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>Raise <a class="reference internal" href="exceptions#ImportError" title="ImportError"><code>ImportError</code></a> when called instead of <a class="reference internal" href="exceptions#NotImplementedError" title="NotImplementedError"><code>NotImplementedError</code></a>. Functionality provided when <a class="reference internal" href="#importlib.abc.Loader.exec_module" title="importlib.abc.Loader.exec_module"><code>exec_module()</code></a> is available.</p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.4: </span>The recommended API for loading a module is <a class="reference internal" href="#importlib.abc.Loader.exec_module" title="importlib.abc.Loader.exec_module"><code>exec_module()</code></a> (and <a class="reference internal" href="#importlib.abc.Loader.create_module" title="importlib.abc.Loader.create_module"><code>create_module()</code></a>). Loaders should implement it instead of <a class="reference internal" href="#importlib.abc.Loader.load_module" title="importlib.abc.Loader.load_module"><code>load_module()</code></a>. The import machinery takes care of all the other responsibilities of <a class="reference internal" href="#importlib.abc.Loader.load_module" title="importlib.abc.Loader.load_module"><code>load_module()</code></a> when <a class="reference internal" href="#importlib.abc.Loader.exec_module" title="importlib.abc.Loader.exec_module"><code>exec_module()</code></a> is implemented.</p> </div> </dd>
</dl> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="importlib.abc.ResourceLoader">
<code>class importlib.abc.ResourceLoader</code> </dt> <dd>
<p>An abstract base class for a <a class="reference internal" href="../glossary#term-loader"><span class="xref std std-term">loader</span></a> which implements the optional <span class="target" id="index-13"></span><a class="pep reference external" href="https://peps.python.org/pep-0302/"><strong>PEP 302</strong></a> protocol for loading arbitrary resources from the storage back-end.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.7: </span>This ABC is deprecated in favour of supporting resource loading through <a class="reference internal" href="importlib.resources.abc#importlib.resources.abc.ResourceReader" title="importlib.resources.abc.ResourceReader"><code>importlib.resources.abc.ResourceReader</code></a>.</p> </div> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.ResourceLoader.get_data">
<code>abstractmethod get_data(path)</code> </dt> <dd>
<p>An abstract method to return the bytes for the data located at <em>path</em>. Loaders that have a file-like storage back-end that allows storing arbitrary data can implement this abstract method to give direct access to the data stored. <a class="reference internal" href="exceptions#OSError" title="OSError"><code>OSError</code></a> is to be raised if the <em>path</em> cannot be found. The <em>path</em> is expected to be constructed using a module’s <a class="reference internal" href="../reference/import#file__" title="__file__"><code>__file__</code></a> attribute or an item from a package’s <a class="reference internal" href="../reference/import#path__" title="__path__"><code>__path__</code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>Raises <a class="reference internal" href="exceptions#OSError" title="OSError"><code>OSError</code></a> instead of <a class="reference internal" href="exceptions#NotImplementedError" title="NotImplementedError"><code>NotImplementedError</code></a>.</p> </div> </dd>
</dl> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="importlib.abc.InspectLoader">
<code>class importlib.abc.InspectLoader</code> </dt> <dd>
<p>An abstract base class for a <a class="reference internal" href="../glossary#term-loader"><span class="xref std std-term">loader</span></a> which implements the optional <span class="target" id="index-14"></span><a class="pep reference external" href="https://peps.python.org/pep-0302/"><strong>PEP 302</strong></a> protocol for loaders that inspect modules.</p> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.InspectLoader.get_code">
<code>get_code(fullname)</code> </dt> <dd>
<p>Return the code object for a module, or <code>None</code> if the module does not have a code object (as would be the case, for example, for a built-in module). Raise an <a class="reference internal" href="exceptions#ImportError" title="ImportError"><code>ImportError</code></a> if loader cannot find the requested module.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>While the method has a default implementation, it is suggested that it be overridden if possible for performance.</p> </div> <div class="versionchanged" id="index-15"> <p><span class="versionmodified changed">Changed in version 3.4: </span>No longer abstract and a concrete implementation is provided.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.InspectLoader.get_source">
<code>abstractmethod get_source(fullname)</code> </dt> <dd>
<p>An abstract method to return the source of a module. It is returned as a text string using <a class="reference internal" href="../glossary#term-universal-newlines"><span class="xref std std-term">universal newlines</span></a>, translating all recognized line separators into <code>'\n'</code> characters. Returns <code>None</code> if no source is available (e.g. a built-in module). Raises <a class="reference internal" href="exceptions#ImportError" title="ImportError"><code>ImportError</code></a> if the loader cannot find the module specified.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>Raises <a class="reference internal" href="exceptions#ImportError" title="ImportError"><code>ImportError</code></a> instead of <a class="reference internal" href="exceptions#NotImplementedError" title="NotImplementedError"><code>NotImplementedError</code></a>.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.InspectLoader.is_package">
<code>is_package(fullname)</code> </dt> <dd>
<p>An optional method to return a true value if the module is a package, a false value otherwise. <a class="reference internal" href="exceptions#ImportError" title="ImportError"><code>ImportError</code></a> is raised if the <a class="reference internal" href="../glossary#term-loader"><span class="xref std std-term">loader</span></a> cannot find the module.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>Raises <a class="reference internal" href="exceptions#ImportError" title="ImportError"><code>ImportError</code></a> instead of <a class="reference internal" href="exceptions#NotImplementedError" title="NotImplementedError"><code>NotImplementedError</code></a>.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.InspectLoader.source_to_code">
<code>static source_to_code(data, path='<string>')</code> </dt> <dd>
<p>Create a code object from Python source.</p> <p>The <em>data</em> argument can be whatever the <a class="reference internal" href="functions#compile" title="compile"><code>compile()</code></a> function supports (i.e. string or bytes). The <em>path</em> argument should be the “path” to where the source code originated from, which can be an abstract concept (e.g. location in a zip file).</p> <p>With the subsequent code object one can execute it in a module by running <code>exec(code, module.__dict__)</code>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>Made the method static.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.InspectLoader.exec_module">
<code>exec_module(module)</code> </dt> <dd>
<p>Implementation of <a class="reference internal" href="#importlib.abc.Loader.exec_module" title="importlib.abc.Loader.exec_module"><code>Loader.exec_module()</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.InspectLoader.load_module">
<code>load_module(fullname)</code> </dt> <dd>
<p>Implementation of <a class="reference internal" href="#importlib.abc.Loader.load_module" title="importlib.abc.Loader.load_module"><code>Loader.load_module()</code></a>.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.4: </span>use <a class="reference internal" href="#importlib.abc.InspectLoader.exec_module" title="importlib.abc.InspectLoader.exec_module"><code>exec_module()</code></a> instead.</p> </div> </dd>
</dl> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="importlib.abc.ExecutionLoader">
<code>class importlib.abc.ExecutionLoader</code> </dt> <dd>
<p>An abstract base class which inherits from <a class="reference internal" href="#importlib.abc.InspectLoader" title="importlib.abc.InspectLoader"><code>InspectLoader</code></a> that, when implemented, helps a module to be executed as a script. The ABC represents an optional <span class="target" id="index-16"></span><a class="pep reference external" href="https://peps.python.org/pep-0302/"><strong>PEP 302</strong></a> protocol.</p> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.ExecutionLoader.get_filename">
<code>abstractmethod get_filename(fullname)</code> </dt> <dd>
<p>An abstract method that is to return the value of <a class="reference internal" href="../reference/import#file__" title="__file__"><code>__file__</code></a> for the specified module. If no path is available, <a class="reference internal" href="exceptions#ImportError" title="ImportError"><code>ImportError</code></a> is raised.</p> <p>If source code is available, then the method should return the path to the source file, regardless of whether a bytecode was used to load the module.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>Raises <a class="reference internal" href="exceptions#ImportError" title="ImportError"><code>ImportError</code></a> instead of <a class="reference internal" href="exceptions#NotImplementedError" title="NotImplementedError"><code>NotImplementedError</code></a>.</p> </div> </dd>
</dl> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="importlib.abc.FileLoader">
<code>class importlib.abc.FileLoader(fullname, path)</code> </dt> <dd>
<p>An abstract base class which inherits from <a class="reference internal" href="#importlib.abc.ResourceLoader" title="importlib.abc.ResourceLoader"><code>ResourceLoader</code></a> and <a class="reference internal" href="#importlib.abc.ExecutionLoader" title="importlib.abc.ExecutionLoader"><code>ExecutionLoader</code></a>, providing concrete implementations of <a class="reference internal" href="#importlib.abc.ResourceLoader.get_data" title="importlib.abc.ResourceLoader.get_data"><code>ResourceLoader.get_data()</code></a> and <a class="reference internal" href="#importlib.abc.ExecutionLoader.get_filename" title="importlib.abc.ExecutionLoader.get_filename"><code>ExecutionLoader.get_filename()</code></a>.</p> <p>The <em>fullname</em> argument is a fully resolved name of the module the loader is to handle. The <em>path</em> argument is the path to the file for the module.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> <dl class="py attribute"> <dt class="sig sig-object py" id="importlib.abc.FileLoader.name">
<code>name</code> </dt> <dd>
<p>The name of the module the loader can handle.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="importlib.abc.FileLoader.path">
<code>path</code> </dt> <dd>
<p>Path to the file of the module.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.FileLoader.load_module">
<code>load_module(fullname)</code> </dt> <dd>
<p>Calls super’s <code>load_module()</code>.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.4: </span>Use <a class="reference internal" href="#importlib.abc.Loader.exec_module" title="importlib.abc.Loader.exec_module"><code>Loader.exec_module()</code></a> instead.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.FileLoader.get_filename">
<code>abstractmethod get_filename(fullname)</code> </dt> <dd>
<p>Returns <a class="reference internal" href="#importlib.abc.FileLoader.path" title="importlib.abc.FileLoader.path"><code>path</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.FileLoader.get_data">
<code>abstractmethod get_data(path)</code> </dt> <dd>
<p>Reads <em>path</em> as a binary file and returns the bytes from it.</p> </dd>
</dl> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="importlib.abc.SourceLoader">
<code>class importlib.abc.SourceLoader</code> </dt> <dd>
<p>An abstract base class for implementing source (and optionally bytecode) file loading. The class inherits from both <a class="reference internal" href="#importlib.abc.ResourceLoader" title="importlib.abc.ResourceLoader"><code>ResourceLoader</code></a> and <a class="reference internal" href="#importlib.abc.ExecutionLoader" title="importlib.abc.ExecutionLoader"><code>ExecutionLoader</code></a>, requiring the implementation of:</p> <ul class="simple"> <li><a class="reference internal" href="#importlib.abc.ResourceLoader.get_data" title="importlib.abc.ResourceLoader.get_data"><code>ResourceLoader.get_data()</code></a></li> <li>
<dl class="simple"> <dt>
<code></code> <a class="reference internal" href="#importlib.abc.ExecutionLoader.get_filename" title="importlib.abc.ExecutionLoader.get_filename"><code>ExecutionLoader.get_filename()</code></a>
</dt>
<dd>
<p>Should only return the path to the source file; sourceless loading is not supported.</p> </dd> </dl> </li> </ul> <p>The abstract methods defined by this class are to add optional bytecode file support. Not implementing these optional methods (or causing them to raise <a class="reference internal" href="exceptions#NotImplementedError" title="NotImplementedError"><code>NotImplementedError</code></a>) causes the loader to only work with source code. Implementing the methods allows the loader to work with source <em>and</em> bytecode files; it does not allow for <em>sourceless</em> loading where only bytecode is provided. Bytecode files are an optimization to speed up loading by removing the parsing step of Python’s compiler, and so no bytecode-specific API is exposed.</p> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.SourceLoader.path_stats">
<code>path_stats(path)</code> </dt> <dd>
<p>Optional abstract method which returns a <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a> containing metadata about the specified path. Supported dictionary keys are:</p> <ul class="simple"> <li>
<code>'mtime'</code> (mandatory): an integer or floating-point number representing the modification time of the source code;</li> <li>
<code>'size'</code> (optional): the size in bytes of the source code.</li> </ul> <p>Any other keys in the dictionary are ignored, to allow for future extensions. If the path cannot be handled, <a class="reference internal" href="exceptions#OSError" title="OSError"><code>OSError</code></a> is raised.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>Raise <a class="reference internal" href="exceptions#OSError" title="OSError"><code>OSError</code></a> instead of <a class="reference internal" href="exceptions#NotImplementedError" title="NotImplementedError"><code>NotImplementedError</code></a>.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.SourceLoader.path_mtime">
<code>path_mtime(path)</code> </dt> <dd>
<p>Optional abstract method which returns the modification time for the specified path.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.3: </span>This method is deprecated in favour of <a class="reference internal" href="#importlib.abc.SourceLoader.path_stats" title="importlib.abc.SourceLoader.path_stats"><code>path_stats()</code></a>. You don’t have to implement it, but it is still available for compatibility purposes. Raise <a class="reference internal" href="exceptions#OSError" title="OSError"><code>OSError</code></a> if the path cannot be handled.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>Raise <a class="reference internal" href="exceptions#OSError" title="OSError"><code>OSError</code></a> instead of <a class="reference internal" href="exceptions#NotImplementedError" title="NotImplementedError"><code>NotImplementedError</code></a>.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.SourceLoader.set_data">
<code>set_data(path, data)</code> </dt> <dd>
<p>Optional abstract method which writes the specified bytes to a file path. Any intermediate directories which do not exist are to be created automatically.</p> <p>When writing to the path fails because the path is read-only (<a class="reference internal" href="errno#errno.EACCES" title="errno.EACCES"><code>errno.EACCES</code></a>/<a class="reference internal" href="exceptions#PermissionError" title="PermissionError"><code>PermissionError</code></a>), do not propagate the exception.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>No longer raises <a class="reference internal" href="exceptions#NotImplementedError" title="NotImplementedError"><code>NotImplementedError</code></a> when called.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.SourceLoader.get_code">
<code>get_code(fullname)</code> </dt> <dd>
<p>Concrete implementation of <a class="reference internal" href="#importlib.abc.InspectLoader.get_code" title="importlib.abc.InspectLoader.get_code"><code>InspectLoader.get_code()</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.SourceLoader.exec_module">
<code>exec_module(module)</code> </dt> <dd>
<p>Concrete implementation of <a class="reference internal" href="#importlib.abc.Loader.exec_module" title="importlib.abc.Loader.exec_module"><code>Loader.exec_module()</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.SourceLoader.load_module">
<code>load_module(fullname)</code> </dt> <dd>
<p>Concrete implementation of <a class="reference internal" href="#importlib.abc.Loader.load_module" title="importlib.abc.Loader.load_module"><code>Loader.load_module()</code></a>.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.4: </span>Use <a class="reference internal" href="#importlib.abc.SourceLoader.exec_module" title="importlib.abc.SourceLoader.exec_module"><code>exec_module()</code></a> instead.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.SourceLoader.get_source">
<code>get_source(fullname)</code> </dt> <dd>
<p>Concrete implementation of <a class="reference internal" href="#importlib.abc.InspectLoader.get_source" title="importlib.abc.InspectLoader.get_source"><code>InspectLoader.get_source()</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.SourceLoader.is_package">
<code>is_package(fullname)</code> </dt> <dd>
<p>Concrete implementation of <a class="reference internal" href="#importlib.abc.InspectLoader.is_package" title="importlib.abc.InspectLoader.is_package"><code>InspectLoader.is_package()</code></a>. A module is determined to be a package if its file path (as provided by <a class="reference internal" href="#importlib.abc.ExecutionLoader.get_filename" title="importlib.abc.ExecutionLoader.get_filename"><code>ExecutionLoader.get_filename()</code></a>) is a file named <code>__init__</code> when the file extension is removed <strong>and</strong> the module name itself does not end in <code>__init__</code>.</p> </dd>
</dl> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="importlib.abc.ResourceReader">
<code>class importlib.abc.ResourceReader</code> </dt> <dd>
<p><em>Superseded by TraversableResources</em></p> <p>An <a class="reference internal" href="../glossary#term-abstract-base-class"><span class="xref std std-term">abstract base class</span></a> to provide the ability to read <em>resources</em>.</p> <p>From the perspective of this ABC, a <em>resource</em> is a binary artifact that is shipped within a package. Typically this is something like a data file that lives next to the <code>__init__.py</code> file of the package. The purpose of this class is to help abstract out the accessing of such data files so that it does not matter if the package and its data file(s) are stored in a e.g. zip file versus on the file system.</p> <p>For any of methods of this class, a <em>resource</em> argument is expected to be a <a class="reference internal" href="../glossary#term-path-like-object"><span class="xref std std-term">path-like object</span></a> which represents conceptually just a file name. This means that no subdirectory paths should be included in the <em>resource</em> argument. This is because the location of the package the reader is for, acts as the “directory”. Hence the metaphor for directories and file names is packages and resources, respectively. This is also why instances of this class are expected to directly correlate to a specific package (instead of potentially representing multiple packages or a module).</p> <p>Loaders that wish to support resource reading are expected to provide a method called <code>get_resource_reader(fullname)</code> which returns an object implementing this ABC’s interface. If the module specified by fullname is not a package, this method should return <a class="reference internal" href="constants#None" title="None"><code>None</code></a>. An object compatible with this ABC should only be returned when the specified module is a package.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> <div class="deprecated-removed"> <p><span class="versionmodified">Deprecated since version 3.12, will be removed in version 3.14: </span>Use <a class="reference internal" href="importlib.resources.abc#importlib.resources.abc.TraversableResources" title="importlib.resources.abc.TraversableResources"><code>importlib.resources.abc.TraversableResources</code></a> instead.</p> </div> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.ResourceReader.open_resource">
<code>abstractmethod open_resource(resource)</code> </dt> <dd>
<p>Returns an opened, <a class="reference internal" href="../glossary#term-file-like-object"><span class="xref std std-term">file-like object</span></a> for binary reading of the <em>resource</em>.</p> <p>If the resource cannot be found, <a class="reference internal" href="exceptions#FileNotFoundError" title="FileNotFoundError"><code>FileNotFoundError</code></a> is raised.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.ResourceReader.resource_path">
<code>abstractmethod resource_path(resource)</code> </dt> <dd>
<p>Returns the file system path to the <em>resource</em>.</p> <p>If the resource does not concretely exist on the file system, raise <a class="reference internal" href="exceptions#FileNotFoundError" title="FileNotFoundError"><code>FileNotFoundError</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.ResourceReader.is_resource">
<code>abstractmethod is_resource(name)</code> </dt> <dd>
<p>Returns <code>True</code> if the named <em>name</em> is considered a resource. <a class="reference internal" href="exceptions#FileNotFoundError" title="FileNotFoundError"><code>FileNotFoundError</code></a> is raised if <em>name</em> does not exist.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.ResourceReader.contents">
<code>abstractmethod contents()</code> </dt> <dd>
<p>Returns an <a class="reference internal" href="../glossary#term-iterable"><span class="xref std std-term">iterable</span></a> of strings over the contents of the package. Do note that it is not required that all names returned by the iterator be actual resources, e.g. it is acceptable to return names for which <a class="reference internal" href="#importlib.abc.ResourceReader.is_resource" title="importlib.abc.ResourceReader.is_resource"><code>is_resource()</code></a> would be false.</p> <p>Allowing non-resource names to be returned is to allow for situations where how a package and its resources are stored are known a priori and the non-resource names would be useful. For instance, returning subdirectory names is allowed so that when it is known that the package and resources are stored on the file system then those subdirectory names can be used directly.</p> <p>The abstract method returns an iterable of no items.</p> </dd>
</dl> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="importlib.abc.Traversable">
<code>class importlib.abc.Traversable</code> </dt> <dd>
<p>An object with a subset of <a class="reference internal" href="pathlib#pathlib.Path" title="pathlib.Path"><code>pathlib.Path</code></a> methods suitable for traversing directories and opening files.</p> <p>For a representation of the object on the file-system, use <a class="reference internal" href="importlib.resources#importlib.resources.as_file" title="importlib.resources.as_file"><code>importlib.resources.as_file()</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.9.</span></p> </div> <div class="deprecated-removed"> <p><span class="versionmodified">Deprecated since version 3.12, will be removed in version 3.14: </span>Use <a class="reference internal" href="importlib.resources.abc#importlib.resources.abc.Traversable" title="importlib.resources.abc.Traversable"><code>importlib.resources.abc.Traversable</code></a> instead.</p> </div> <dl class="py attribute"> <dt class="sig sig-object py" id="importlib.abc.Traversable.name">
<code>name</code> </dt> <dd>
<p>Abstract. The base name of this object without any parent references.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.Traversable.iterdir">
<code>abstractmethod iterdir()</code> </dt> <dd>
<p>Yield <code>Traversable</code> objects in <code>self</code>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.Traversable.is_dir">
<code>abstractmethod is_dir()</code> </dt> <dd>
<p>Return <code>True</code> if <code>self</code> is a directory.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.Traversable.is_file">
<code>abstractmethod is_file()</code> </dt> <dd>
<p>Return <code>True</code> if <code>self</code> is a file.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.Traversable.joinpath">
<code>abstractmethod joinpath(child)</code> </dt> <dd>
<p>Return Traversable child in <code>self</code>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.Traversable.__truediv__">
<code>abstractmethod __truediv__(child)</code> </dt> <dd>
<p>Return <code>Traversable</code> child in <code>self</code>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.Traversable.open">
<code>abstractmethod open(mode='r', *args, **kwargs)</code> </dt> <dd>
<p><em>mode</em> may be ‘r’ or ‘rb’ to open as text or binary. Return a handle suitable for reading (same as <a class="reference internal" href="pathlib#pathlib.Path.open" title="pathlib.Path.open"><code>pathlib.Path.open</code></a>).</p> <p>When opening as text, accepts encoding parameters such as those accepted by <a class="reference internal" href="io#io.TextIOWrapper" title="io.TextIOWrapper"><code>io.TextIOWrapper</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.Traversable.read_bytes">
<code>read_bytes()</code> </dt> <dd>
<p>Read contents of <code>self</code> as bytes.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.Traversable.read_text">
<code>read_text(encoding=None)</code> </dt> <dd>
<p>Read contents of <code>self</code> as text.</p> </dd>
</dl> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="importlib.abc.TraversableResources">
<code>class importlib.abc.TraversableResources</code> </dt> <dd>
<p>An abstract base class for resource readers capable of serving the <a class="reference internal" href="importlib.resources#importlib.resources.files" title="importlib.resources.files"><code>importlib.resources.files()</code></a> interface. Subclasses <a class="reference internal" href="importlib.resources.abc#importlib.resources.abc.ResourceReader" title="importlib.resources.abc.ResourceReader"><code>importlib.resources.abc.ResourceReader</code></a> and provides concrete implementations of the <a class="reference internal" href="importlib.resources.abc#importlib.resources.abc.ResourceReader" title="importlib.resources.abc.ResourceReader"><code>importlib.resources.abc.ResourceReader</code></a>’s abstract methods. Therefore, any loader supplying <a class="reference internal" href="#importlib.abc.TraversableResources" title="importlib.abc.TraversableResources"><code>importlib.abc.TraversableResources</code></a> also supplies ResourceReader.</p> <p>Loaders that wish to support resource reading are expected to implement this interface.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.9.</span></p> </div> <div class="deprecated-removed"> <p><span class="versionmodified">Deprecated since version 3.12, will be removed in version 3.14: </span>Use <a class="reference internal" href="importlib.resources.abc#importlib.resources.abc.TraversableResources" title="importlib.resources.abc.TraversableResources"><code>importlib.resources.abc.TraversableResources</code></a> instead.</p> </div> <dl class="py method"> <dt class="sig sig-object py" id="importlib.abc.TraversableResources.files">
<code>abstractmethod files()</code> </dt> <dd>
<p>Returns a <a class="reference internal" href="importlib.resources.abc#importlib.resources.abc.Traversable" title="importlib.resources.abc.Traversable"><code>importlib.resources.abc.Traversable</code></a> object for the loaded package.</p> </dd>
</dl> </dd>
</dl> </section> <section id="module-importlib.machinery"> <span id="importlib-machinery-importers-and-path-hooks"></span><h2>importlib.machinery – Importers and path hooks</h2> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/importlib/machinery.py">Lib/importlib/machinery.py</a></p> <p>This module contains the various objects that help <a class="reference internal" href="../reference/simple_stmts#import"><code>import</code></a> find and load modules.</p> <dl class="py attribute"> <dt class="sig sig-object py" id="importlib.machinery.SOURCE_SUFFIXES">
<code>importlib.machinery.SOURCE_SUFFIXES</code> </dt> <dd>
<p>A list of strings representing the recognized file suffixes for source modules.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="importlib.machinery.DEBUG_BYTECODE_SUFFIXES">
<code>importlib.machinery.DEBUG_BYTECODE_SUFFIXES</code> </dt> <dd>
<p>A list of strings representing the file suffixes for non-optimized bytecode modules.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.5: </span>Use <a class="reference internal" href="#importlib.machinery.BYTECODE_SUFFIXES" title="importlib.machinery.BYTECODE_SUFFIXES"><code>BYTECODE_SUFFIXES</code></a> instead.</p> </div> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES">
<code>importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES</code> </dt> <dd>
<p>A list of strings representing the file suffixes for optimized bytecode modules.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.5: </span>Use <a class="reference internal" href="#importlib.machinery.BYTECODE_SUFFIXES" title="importlib.machinery.BYTECODE_SUFFIXES"><code>BYTECODE_SUFFIXES</code></a> instead.</p> </div> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="importlib.machinery.BYTECODE_SUFFIXES">
<code>importlib.machinery.BYTECODE_SUFFIXES</code> </dt> <dd>
<p>A list of strings representing the recognized file suffixes for bytecode modules (including the leading dot).</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>The value is no longer dependent on <code>__debug__</code>.</p> </div> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="importlib.machinery.EXTENSION_SUFFIXES">
<code>importlib.machinery.EXTENSION_SUFFIXES</code> </dt> <dd>
<p>A list of strings representing the recognized file suffixes for extension modules.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="importlib.machinery.all_suffixes">
<code>importlib.machinery.all_suffixes()</code> </dt> <dd>
<p>Returns a combined list of strings representing all file suffixes for modules recognized by the standard import machinery. This is a helper for code which simply needs to know if a filesystem path potentially refers to a module without needing any details on the kind of module (for example, <a class="reference internal" href="inspect#inspect.getmodulename" title="inspect.getmodulename"><code>inspect.getmodulename()</code></a>).</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="importlib.machinery.BuiltinImporter">
<code>class importlib.machinery.BuiltinImporter</code> </dt> <dd>
<p>An <a class="reference internal" href="../glossary#term-importer"><span class="xref std std-term">importer</span></a> for built-in modules. All known built-in modules are listed in <a class="reference internal" href="sys#sys.builtin_module_names" title="sys.builtin_module_names"><code>sys.builtin_module_names</code></a>. This class implements the <a class="reference internal" href="#importlib.abc.MetaPathFinder" title="importlib.abc.MetaPathFinder"><code>importlib.abc.MetaPathFinder</code></a> and <a class="reference internal" href="#importlib.abc.InspectLoader" title="importlib.abc.InspectLoader"><code>importlib.abc.InspectLoader</code></a> ABCs.</p> <p>Only class methods are defined by this class to alleviate the need for instantiation.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>As part of <span class="target" id="index-17"></span><a class="pep reference external" href="https://peps.python.org/pep-0489/"><strong>PEP 489</strong></a>, the builtin importer now implements <code>Loader.create_module()</code> and <code>Loader.exec_module()</code></p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="importlib.machinery.FrozenImporter">
<code>class importlib.machinery.FrozenImporter</code> </dt> <dd>
<p>An <a class="reference internal" href="../glossary#term-importer"><span class="xref std std-term">importer</span></a> for frozen modules. This class implements the <a class="reference internal" href="#importlib.abc.MetaPathFinder" title="importlib.abc.MetaPathFinder"><code>importlib.abc.MetaPathFinder</code></a> and <a class="reference internal" href="#importlib.abc.InspectLoader" title="importlib.abc.InspectLoader"><code>importlib.abc.InspectLoader</code></a> ABCs.</p> <p>Only class methods are defined by this class to alleviate the need for instantiation.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>Gained <code>create_module()</code> and <code>exec_module()</code> methods.</p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="importlib.machinery.WindowsRegistryFinder">
<code>class importlib.machinery.WindowsRegistryFinder</code> </dt> <dd>
<p><a class="reference internal" href="../glossary#term-finder"><span class="xref std std-term">Finder</span></a> for modules declared in the Windows registry. This class implements the <a class="reference internal" href="#importlib.abc.MetaPathFinder" title="importlib.abc.MetaPathFinder"><code>importlib.abc.MetaPathFinder</code></a> ABC.</p> <p>Only class methods are defined by this class to alleviate the need for instantiation.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.6: </span>Use <a class="reference internal" href="site#module-site" title="site: Module responsible for site-specific configuration."><code>site</code></a> configuration instead. Future versions of Python may not enable this finder by default.</p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="importlib.machinery.PathFinder">
<code>class importlib.machinery.PathFinder</code> </dt> <dd>
<p>A <a class="reference internal" href="../glossary#term-finder"><span class="xref std std-term">Finder</span></a> for <a class="reference internal" href="sys#sys.path" title="sys.path"><code>sys.path</code></a> and package <code>__path__</code> attributes. This class implements the <a class="reference internal" href="#importlib.abc.MetaPathFinder" title="importlib.abc.MetaPathFinder"><code>importlib.abc.MetaPathFinder</code></a> ABC.</p> <p>Only class methods are defined by this class to alleviate the need for instantiation.</p> <dl class="py method"> <dt class="sig sig-object py" id="importlib.machinery.PathFinder.find_spec">
<code>classmethod find_spec(fullname, path=None, target=None)</code> </dt> <dd>
<p>Class method that attempts to find a <a class="reference internal" href="../glossary#term-module-spec"><span class="xref std std-term">spec</span></a> for the module specified by <em>fullname</em> on <a class="reference internal" href="sys#sys.path" title="sys.path"><code>sys.path</code></a> or, if defined, on <em>path</em>. For each path entry that is searched, <a class="reference internal" href="sys#sys.path_importer_cache" title="sys.path_importer_cache"><code>sys.path_importer_cache</code></a> is checked. If a non-false object is found then it is used as the <a class="reference internal" href="../glossary#term-path-entry-finder"><span class="xref std std-term">path entry finder</span></a> to look for the module being searched for. If no entry is found in <a class="reference internal" href="sys#sys.path_importer_cache" title="sys.path_importer_cache"><code>sys.path_importer_cache</code></a>, then <a class="reference internal" href="sys#sys.path_hooks" title="sys.path_hooks"><code>sys.path_hooks</code></a> is searched for a finder for the path entry and, if found, is stored in <a class="reference internal" href="sys#sys.path_importer_cache" title="sys.path_importer_cache"><code>sys.path_importer_cache</code></a> along with being queried about the module. If no finder is ever found then <code>None</code> is both stored in the cache and returned.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>If the current working directory – represented by an empty string – is no longer valid then <code>None</code> is returned but no value is cached in <a class="reference internal" href="sys#sys.path_importer_cache" title="sys.path_importer_cache"><code>sys.path_importer_cache</code></a>.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.machinery.PathFinder.invalidate_caches">
<code>classmethod invalidate_caches()</code> </dt> <dd>
<p>Calls <a class="reference internal" href="#importlib.abc.PathEntryFinder.invalidate_caches" title="importlib.abc.PathEntryFinder.invalidate_caches"><code>importlib.abc.PathEntryFinder.invalidate_caches()</code></a> on all finders stored in <a class="reference internal" href="sys#sys.path_importer_cache" title="sys.path_importer_cache"><code>sys.path_importer_cache</code></a> that define the method. Otherwise entries in <a class="reference internal" href="sys#sys.path_importer_cache" title="sys.path_importer_cache"><code>sys.path_importer_cache</code></a> set to <code>None</code> are deleted.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>Entries of <code>None</code> in <a class="reference internal" href="sys#sys.path_importer_cache" title="sys.path_importer_cache"><code>sys.path_importer_cache</code></a> are deleted.</p> </div> </dd>
</dl> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>Calls objects in <a class="reference internal" href="sys#sys.path_hooks" title="sys.path_hooks"><code>sys.path_hooks</code></a> with the current working directory for <code>''</code> (i.e. the empty string).</p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="importlib.machinery.FileFinder">
<code>class importlib.machinery.FileFinder(path, *loader_details)</code> </dt> <dd>
<p>A concrete implementation of <a class="reference internal" href="#importlib.abc.PathEntryFinder" title="importlib.abc.PathEntryFinder"><code>importlib.abc.PathEntryFinder</code></a> which caches results from the file system.</p> <p>The <em>path</em> argument is the directory for which the finder is in charge of searching.</p> <p>The <em>loader_details</em> argument is a variable number of 2-item tuples each containing a loader and a sequence of file suffixes the loader recognizes. The loaders are expected to be callables which accept two arguments of the module’s name and the path to the file found.</p> <p>The finder will cache the directory contents as necessary, making stat calls for each module search to verify the cache is not outdated. Because cache staleness relies upon the granularity of the operating system’s state information of the file system, there is a potential race condition of searching for a module, creating a new file, and then searching for the module the new file represents. If the operations happen fast enough to fit within the granularity of stat calls, then the module search will fail. To prevent this from happening, when you create a module dynamically, make sure to call <a class="reference internal" href="#importlib.invalidate_caches" title="importlib.invalidate_caches"><code>importlib.invalidate_caches()</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> <dl class="py attribute"> <dt class="sig sig-object py" id="importlib.machinery.FileFinder.path">
<code>path</code> </dt> <dd>
<p>The path the finder will search in.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.machinery.FileFinder.find_spec">
<code>find_spec(fullname, target=None)</code> </dt> <dd>
<p>Attempt to find the spec to handle <em>fullname</em> within <a class="reference internal" href="#importlib.machinery.FileFinder.path" title="importlib.machinery.FileFinder.path"><code>path</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.machinery.FileFinder.invalidate_caches">
<code>invalidate_caches()</code> </dt> <dd>
<p>Clear out the internal cache.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.machinery.FileFinder.path_hook">
<code>classmethod path_hook(*loader_details)</code> </dt> <dd>
<p>A class method which returns a closure for use on <a class="reference internal" href="sys#sys.path_hooks" title="sys.path_hooks"><code>sys.path_hooks</code></a>. An instance of <a class="reference internal" href="#importlib.machinery.FileFinder" title="importlib.machinery.FileFinder"><code>FileFinder</code></a> is returned by the closure using the path argument given to the closure directly and <em>loader_details</em> indirectly.</p> <p>If the argument to the closure is not an existing directory, <a class="reference internal" href="exceptions#ImportError" title="ImportError"><code>ImportError</code></a> is raised.</p> </dd>
</dl> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="importlib.machinery.SourceFileLoader">
<code>class importlib.machinery.SourceFileLoader(fullname, path)</code> </dt> <dd>
<p>A concrete implementation of <a class="reference internal" href="#importlib.abc.SourceLoader" title="importlib.abc.SourceLoader"><code>importlib.abc.SourceLoader</code></a> by subclassing <a class="reference internal" href="#importlib.abc.FileLoader" title="importlib.abc.FileLoader"><code>importlib.abc.FileLoader</code></a> and providing some concrete implementations of other methods.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> <dl class="py attribute"> <dt class="sig sig-object py" id="importlib.machinery.SourceFileLoader.name">
<code>name</code> </dt> <dd>
<p>The name of the module that this loader will handle.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="importlib.machinery.SourceFileLoader.path">
<code>path</code> </dt> <dd>
<p>The path to the source file.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.machinery.SourceFileLoader.is_package">
<code>is_package(fullname)</code> </dt> <dd>
<p>Return <code>True</code> if <a class="reference internal" href="#importlib.machinery.SourceFileLoader.path" title="importlib.machinery.SourceFileLoader.path"><code>path</code></a> appears to be for a package.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.machinery.SourceFileLoader.path_stats">
<code>path_stats(path)</code> </dt> <dd>
<p>Concrete implementation of <a class="reference internal" href="#importlib.abc.SourceLoader.path_stats" title="importlib.abc.SourceLoader.path_stats"><code>importlib.abc.SourceLoader.path_stats()</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.machinery.SourceFileLoader.set_data">
<code>set_data(path, data)</code> </dt> <dd>
<p>Concrete implementation of <a class="reference internal" href="#importlib.abc.SourceLoader.set_data" title="importlib.abc.SourceLoader.set_data"><code>importlib.abc.SourceLoader.set_data()</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.machinery.SourceFileLoader.load_module">
<code>load_module(name=None)</code> </dt> <dd>
<p>Concrete implementation of <a class="reference internal" href="#importlib.abc.Loader.load_module" title="importlib.abc.Loader.load_module"><code>importlib.abc.Loader.load_module()</code></a> where specifying the name of the module to load is optional.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.6: </span>Use <a class="reference internal" href="#importlib.abc.Loader.exec_module" title="importlib.abc.Loader.exec_module"><code>importlib.abc.Loader.exec_module()</code></a> instead.</p> </div> </dd>
</dl> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="importlib.machinery.SourcelessFileLoader">
<code>class importlib.machinery.SourcelessFileLoader(fullname, path)</code> </dt> <dd>
<p>A concrete implementation of <a class="reference internal" href="#importlib.abc.FileLoader" title="importlib.abc.FileLoader"><code>importlib.abc.FileLoader</code></a> which can import bytecode files (i.e. no source code files exist).</p> <p>Please note that direct use of bytecode files (and thus not source code files) inhibits your modules from being usable by all Python implementations or new versions of Python which change the bytecode format.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> <dl class="py attribute"> <dt class="sig sig-object py" id="importlib.machinery.SourcelessFileLoader.name">
<code>name</code> </dt> <dd>
<p>The name of the module the loader will handle.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="importlib.machinery.SourcelessFileLoader.path">
<code>path</code> </dt> <dd>
<p>The path to the bytecode file.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.machinery.SourcelessFileLoader.is_package">
<code>is_package(fullname)</code> </dt> <dd>
<p>Determines if the module is a package based on <a class="reference internal" href="#importlib.machinery.SourcelessFileLoader.path" title="importlib.machinery.SourcelessFileLoader.path"><code>path</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.machinery.SourcelessFileLoader.get_code">
<code>get_code(fullname)</code> </dt> <dd>
<p>Returns the code object for <a class="reference internal" href="#importlib.machinery.SourcelessFileLoader.name" title="importlib.machinery.SourcelessFileLoader.name"><code>name</code></a> created from <a class="reference internal" href="#importlib.machinery.SourcelessFileLoader.path" title="importlib.machinery.SourcelessFileLoader.path"><code>path</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.machinery.SourcelessFileLoader.get_source">
<code>get_source(fullname)</code> </dt> <dd>
<p>Returns <code>None</code> as bytecode files have no source when this loader is used.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.machinery.SourcelessFileLoader.load_module">
<code>load_module(name=None)</code> </dt> <dd></dd>
</dl> <p>Concrete implementation of <a class="reference internal" href="#importlib.abc.Loader.load_module" title="importlib.abc.Loader.load_module"><code>importlib.abc.Loader.load_module()</code></a> where specifying the name of the module to load is optional.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.6: </span>Use <a class="reference internal" href="#importlib.abc.Loader.exec_module" title="importlib.abc.Loader.exec_module"><code>importlib.abc.Loader.exec_module()</code></a> instead.</p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="importlib.machinery.ExtensionFileLoader">
<code>class importlib.machinery.ExtensionFileLoader(fullname, path)</code> </dt> <dd>
<p>A concrete implementation of <a class="reference internal" href="#importlib.abc.ExecutionLoader" title="importlib.abc.ExecutionLoader"><code>importlib.abc.ExecutionLoader</code></a> for extension modules.</p> <p>The <em>fullname</em> argument specifies the name of the module the loader is to support. The <em>path</em> argument is the path to the extension module’s file.</p> <p>Note that, by default, importing an extension module will fail in subinterpreters if it doesn’t implement multi-phase init (see <span class="target" id="index-18"></span><a class="pep reference external" href="https://peps.python.org/pep-0489/"><strong>PEP 489</strong></a>), even if it would otherwise import successfully.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Multi-phase init is now required for use in subinterpreters.</p> </div> <dl class="py attribute"> <dt class="sig sig-object py" id="importlib.machinery.ExtensionFileLoader.name">
<code>name</code> </dt> <dd>
<p>Name of the module the loader supports.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="importlib.machinery.ExtensionFileLoader.path">
<code>path</code> </dt> <dd>
<p>Path to the extension module.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.machinery.ExtensionFileLoader.create_module">
<code>create_module(spec)</code> </dt> <dd>
<p>Creates the module object from the given specification in accordance with <span class="target" id="index-19"></span><a class="pep reference external" href="https://peps.python.org/pep-0489/"><strong>PEP 489</strong></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.machinery.ExtensionFileLoader.exec_module">
<code>exec_module(module)</code> </dt> <dd>
<p>Initializes the given module object in accordance with <span class="target" id="index-20"></span><a class="pep reference external" href="https://peps.python.org/pep-0489/"><strong>PEP 489</strong></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.machinery.ExtensionFileLoader.is_package">
<code>is_package(fullname)</code> </dt> <dd>
<p>Returns <code>True</code> if the file path points to a package’s <code>__init__</code> module based on <a class="reference internal" href="#importlib.machinery.EXTENSION_SUFFIXES" title="importlib.machinery.EXTENSION_SUFFIXES"><code>EXTENSION_SUFFIXES</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.machinery.ExtensionFileLoader.get_code">
<code>get_code(fullname)</code> </dt> <dd>
<p>Returns <code>None</code> as extension modules lack a code object.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.machinery.ExtensionFileLoader.get_source">
<code>get_source(fullname)</code> </dt> <dd>
<p>Returns <code>None</code> as extension modules do not have source code.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="importlib.machinery.ExtensionFileLoader.get_filename">
<code>get_filename(fullname)</code> </dt> <dd>
<p>Returns <a class="reference internal" href="#importlib.machinery.ExtensionFileLoader.path" title="importlib.machinery.ExtensionFileLoader.path"><code>path</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> </dd>
</dl> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="importlib.machinery.NamespaceLoader">
<code>class importlib.machinery.NamespaceLoader(name, path, path_finder)</code> </dt> <dd>
<p>A concrete implementation of <a class="reference internal" href="#importlib.abc.InspectLoader" title="importlib.abc.InspectLoader"><code>importlib.abc.InspectLoader</code></a> for namespace packages. This is an alias for a private class and is only made public for introspecting the <code>__loader__</code> attribute on namespace packages:</p> <pre data-language="python">>>> from importlib.machinery import NamespaceLoader
>>> import my_namespace
>>> isinstance(my_namespace.__loader__, NamespaceLoader)
True
>>> import importlib.abc
>>> isinstance(my_namespace.__loader__, importlib.abc.Loader)
True
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="importlib.machinery.ModuleSpec">
<code>class importlib.machinery.ModuleSpec(name, loader, *, origin=None, loader_state=None, is_package=None)</code> </dt> <dd>
<p>A specification for a module’s import-system-related state. This is typically exposed as the module’s <a class="reference internal" href="../reference/import#spec__" title="__spec__"><code>__spec__</code></a> attribute. In the descriptions below, the names in parentheses give the corresponding attribute available directly on the module object, e.g. <code>module.__spec__.origin == module.__file__</code>. Note, however, that while the <em>values</em> are usually equivalent, they can differ since there is no synchronization between the two objects. For example, it is possible to update the module’s <a class="reference internal" href="../reference/import#file__" title="__file__"><code>__file__</code></a> at runtime and this will not be automatically reflected in the module’s <code>__spec__.origin</code>, and vice versa.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> <dl class="py attribute"> <dt class="sig sig-object py" id="importlib.machinery.ModuleSpec.name">
<code>name</code> </dt> <dd></dd>
</dl> <p>(<a class="reference internal" href="../reference/import#name__" title="__name__"><code>__name__</code></a>)</p> <p>The module’s fully qualified name. The <a class="reference internal" href="../glossary#term-finder"><span class="xref std std-term">finder</span></a> should always set this attribute to a non-empty string.</p> <dl class="py attribute"> <dt class="sig sig-object py" id="importlib.machinery.ModuleSpec.loader">
<code>loader</code> </dt> <dd></dd>
</dl> <p>(<a class="reference internal" href="../reference/import#loader__" title="__loader__"><code>__loader__</code></a>)</p> <p>The <a class="reference internal" href="../glossary#term-loader"><span class="xref std std-term">loader</span></a> used to load the module. The <a class="reference internal" href="../glossary#term-finder"><span class="xref std std-term">finder</span></a> should always set this attribute.</p> <dl class="py attribute"> <dt class="sig sig-object py" id="importlib.machinery.ModuleSpec.origin">
<code>origin</code> </dt> <dd></dd>
</dl> <p>(<a class="reference internal" href="../reference/import#file__" title="__file__"><code>__file__</code></a>)</p> <p>The location the <a class="reference internal" href="../glossary#term-loader"><span class="xref std std-term">loader</span></a> should use to load the module. For example, for modules loaded from a .py file this is the filename. The <a class="reference internal" href="../glossary#term-finder"><span class="xref std std-term">finder</span></a> should always set this attribute to a meaningful value for the <a class="reference internal" href="../glossary#term-loader"><span class="xref std std-term">loader</span></a> to use. In the uncommon case that there is not one (like for namespace packages), it should be set to <code>None</code>.</p> <dl class="py attribute"> <dt class="sig sig-object py" id="importlib.machinery.ModuleSpec.submodule_search_locations">
<code>submodule_search_locations</code> </dt> <dd></dd>
</dl> <p>(<a class="reference internal" href="../reference/import#path__" title="__path__"><code>__path__</code></a>)</p> <p>The list of locations where the package’s submodules will be found. Most of the time this is a single directory. The <a class="reference internal" href="../glossary#term-finder"><span class="xref std std-term">finder</span></a> should set this attribute to a list, even an empty one, to indicate to the import system that the module is a package. It should be set to <code>None</code> for non-package modules. It is set automatically later to a special object for namespace packages.</p> <dl class="py attribute"> <dt class="sig sig-object py" id="importlib.machinery.ModuleSpec.loader_state">
<code>loader_state</code> </dt> <dd></dd>
</dl> <p>The <a class="reference internal" href="../glossary#term-finder"><span class="xref std std-term">finder</span></a> may set this attribute to an object containing additional, module-specific data to use when loading the module. Otherwise it should be set to <code>None</code>.</p> <dl class="py attribute"> <dt class="sig sig-object py" id="importlib.machinery.ModuleSpec.cached">
<code>cached</code> </dt> <dd></dd>
</dl> <p>(<a class="reference internal" href="../reference/import#cached__" title="__cached__"><code>__cached__</code></a>)</p> <p>The filename of a compiled version of the module’s code. The <a class="reference internal" href="../glossary#term-finder"><span class="xref std std-term">finder</span></a> should always set this attribute but it may be <code>None</code> for modules that do not need compiled code stored.</p> <dl class="py attribute"> <dt class="sig sig-object py" id="importlib.machinery.ModuleSpec.parent">
<code>parent</code> </dt> <dd></dd>
</dl> <p>(<a class="reference internal" href="../reference/import#package__" title="__package__"><code>__package__</code></a>)</p> <p>(Read-only) The fully qualified name of the package the module is in (or the empty string for a top-level module). If the module is a package then this is the same as <a class="reference internal" href="#importlib.machinery.ModuleSpec.name" title="importlib.machinery.ModuleSpec.name"><code>name</code></a>.</p> <dl class="py attribute"> <dt class="sig sig-object py" id="importlib.machinery.ModuleSpec.has_location">
<code>has_location</code> </dt> <dd></dd>
</dl> <dl class="simple"> <dt>
<code>True if the spec’s origin refers to a loadable location,</code> </dt>
<dd>
<p><code>False</code> otherwise. This value impacts how <a class="reference internal" href="#importlib.machinery.ModuleSpec.origin" title="importlib.machinery.ModuleSpec.origin"><code>origin</code></a> is interpreted and how the module’s <a class="reference internal" href="../reference/import#file__" title="__file__"><code>__file__</code></a> is populated.</p> </dd> </dl> </dd>
</dl> </section> <section id="module-importlib.util"> <span id="importlib-util-utility-code-for-importers"></span><h2>importlib.util – Utility code for importers</h2> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/importlib/util.py">Lib/importlib/util.py</a></p> <p>This module contains the various objects that help in the construction of an <a class="reference internal" href="../glossary#term-importer"><span class="xref std std-term">importer</span></a>.</p> <dl class="py attribute"> <dt class="sig sig-object py" id="importlib.util.MAGIC_NUMBER">
<code>importlib.util.MAGIC_NUMBER</code> </dt> <dd>
<p>The bytes which represent the bytecode version number. If you need help with loading/writing bytecode then consider <a class="reference internal" href="#importlib.abc.SourceLoader" title="importlib.abc.SourceLoader"><code>importlib.abc.SourceLoader</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="importlib.util.cache_from_source">
<code>importlib.util.cache_from_source(path, debug_override=None, *, optimization=None)</code> </dt> <dd>
<p>Return the <span class="target" id="index-21"></span><a class="pep reference external" href="https://peps.python.org/pep-3147/"><strong>PEP 3147</strong></a>/<span class="target" id="index-22"></span><a class="pep reference external" href="https://peps.python.org/pep-0488/"><strong>PEP 488</strong></a> path to the byte-compiled file associated with the source <em>path</em>. For example, if <em>path</em> is <code>/foo/bar/baz.py</code> the return value would be <code>/foo/bar/__pycache__/baz.cpython-32.pyc</code> for Python 3.2. The <code>cpython-32</code> string comes from the current magic tag (see <code>get_tag()</code>; if <code>sys.implementation.cache_tag</code> is not defined then <a class="reference internal" href="exceptions#NotImplementedError" title="NotImplementedError"><code>NotImplementedError</code></a> will be raised).</p> <p>The <em>optimization</em> parameter is used to specify the optimization level of the bytecode file. An empty string represents no optimization, so <code>/foo/bar/baz.py</code> with an <em>optimization</em> of <code>''</code> will result in a bytecode path of <code>/foo/bar/__pycache__/baz.cpython-32.pyc</code>. <code>None</code> causes the interpreter’s optimization level to be used. Any other value’s string representation is used, so <code>/foo/bar/baz.py</code> with an <em>optimization</em> of <code>2</code> will lead to the bytecode path of <code>/foo/bar/__pycache__/baz.cpython-32.opt-2.pyc</code>. The string representation of <em>optimization</em> can only be alphanumeric, else <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> is raised.</p> <p>The <em>debug_override</em> parameter is deprecated and can be used to override the system’s value for <code>__debug__</code>. A <code>True</code> value is the equivalent of setting <em>optimization</em> to the empty string. A <code>False</code> value is the same as setting <em>optimization</em> to <code>1</code>. If both <em>debug_override</em> an <em>optimization</em> are not <code>None</code> then <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> is raised.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>The <em>optimization</em> parameter was added and the <em>debug_override</em> parameter was deprecated.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>Accepts a <a class="reference internal" href="../glossary#term-path-like-object"><span class="xref std std-term">path-like object</span></a>.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="importlib.util.source_from_cache">
<code>importlib.util.source_from_cache(path)</code> </dt> <dd>
<p>Given the <em>path</em> to a <span class="target" id="index-23"></span><a class="pep reference external" href="https://peps.python.org/pep-3147/"><strong>PEP 3147</strong></a> file name, return the associated source code file path. For example, if <em>path</em> is <code>/foo/bar/__pycache__/baz.cpython-32.pyc</code> the returned path would be <code>/foo/bar/baz.py</code>. <em>path</em> need not exist, however if it does not conform to <span class="target" id="index-24"></span><a class="pep reference external" href="https://peps.python.org/pep-3147/"><strong>PEP 3147</strong></a> or <span class="target" id="index-25"></span><a class="pep reference external" href="https://peps.python.org/pep-0488/"><strong>PEP 488</strong></a> format, a <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> is raised. If <code>sys.implementation.cache_tag</code> is not defined, <a class="reference internal" href="exceptions#NotImplementedError" title="NotImplementedError"><code>NotImplementedError</code></a> is raised.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>Accepts a <a class="reference internal" href="../glossary#term-path-like-object"><span class="xref std std-term">path-like object</span></a>.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="importlib.util.decode_source">
<code>importlib.util.decode_source(source_bytes)</code> </dt> <dd>
<p>Decode the given bytes representing source code and return it as a string with universal newlines (as required by <a class="reference internal" href="#importlib.abc.InspectLoader.get_source" title="importlib.abc.InspectLoader.get_source"><code>importlib.abc.InspectLoader.get_source()</code></a>).</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="importlib.util.resolve_name">
<code>importlib.util.resolve_name(name, package)</code> </dt> <dd>
<p>Resolve a relative module name to an absolute one.</p> <p>If <strong>name</strong> has no leading dots, then <strong>name</strong> is simply returned. This allows for usage such as <code>importlib.util.resolve_name('sys', __spec__.parent)</code> without doing a check to see if the <strong>package</strong> argument is needed.</p> <p><a class="reference internal" href="exceptions#ImportError" title="ImportError"><code>ImportError</code></a> is raised if <strong>name</strong> is a relative module name but <strong>package</strong> is a false value (e.g. <code>None</code> or the empty string). <a class="reference internal" href="exceptions#ImportError" title="ImportError"><code>ImportError</code></a> is also raised if a relative name would escape its containing package (e.g. requesting <code>..bacon</code> from within the <code>spam</code> package).</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.9: </span>To improve consistency with import statements, raise <a class="reference internal" href="exceptions#ImportError" title="ImportError"><code>ImportError</code></a> instead of <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> for invalid relative import attempts.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="importlib.util.find_spec">
<code>importlib.util.find_spec(name, package=None)</code> </dt> <dd>
<p>Find the <a class="reference internal" href="../glossary#term-module-spec"><span class="xref std std-term">spec</span></a> for a module, optionally relative to the specified <strong>package</strong> name. If the module is in <a class="reference internal" href="sys#sys.modules" title="sys.modules"><code>sys.modules</code></a>, then <code>sys.modules[name].__spec__</code> is returned (unless the spec would be <code>None</code> or is not set, in which case <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> is raised). Otherwise a search using <a class="reference internal" href="sys#sys.meta_path" title="sys.meta_path"><code>sys.meta_path</code></a> is done. <code>None</code> is returned if no spec is found.</p> <p>If <strong>name</strong> is for a submodule (contains a dot), the parent module is automatically imported.</p> <p><strong>name</strong> and <strong>package</strong> work the same as for <code>import_module()</code>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>Raises <a class="reference internal" href="exceptions#ModuleNotFoundError" title="ModuleNotFoundError"><code>ModuleNotFoundError</code></a> instead of <a class="reference internal" href="exceptions#AttributeError" title="AttributeError"><code>AttributeError</code></a> if <strong>package</strong> is in fact not a package (i.e. lacks a <a class="reference internal" href="../reference/import#path__" title="__path__"><code>__path__</code></a> attribute).</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="importlib.util.module_from_spec">
<code>importlib.util.module_from_spec(spec)</code> </dt> <dd>
<p>Create a new module based on <strong>spec</strong> and <a class="reference internal" href="#importlib.abc.Loader.create_module" title="importlib.abc.Loader.create_module"><code>spec.loader.create_module</code></a>.</p> <p>If <a class="reference internal" href="#importlib.abc.Loader.create_module" title="importlib.abc.Loader.create_module"><code>spec.loader.create_module</code></a> does not return <code>None</code>, then any pre-existing attributes will not be reset. Also, no <a class="reference internal" href="exceptions#AttributeError" title="AttributeError"><code>AttributeError</code></a> will be raised if triggered while accessing <strong>spec</strong> or setting an attribute on the module.</p> <p>This function is preferred over using <a class="reference internal" href="types#types.ModuleType" title="types.ModuleType"><code>types.ModuleType</code></a> to create a new module as <strong>spec</strong> is used to set as many import-controlled attributes on the module as possible.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.</span></p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="importlib.util.spec_from_loader">
<code>importlib.util.spec_from_loader(name, loader, *, origin=None, is_package=None)</code> </dt> <dd>
<p>A factory function for creating a <a class="reference internal" href="#importlib.machinery.ModuleSpec" title="importlib.machinery.ModuleSpec"><code>ModuleSpec</code></a> instance based on a loader. The parameters have the same meaning as they do for ModuleSpec. The function uses available <a class="reference internal" href="../glossary#term-loader"><span class="xref std std-term">loader</span></a> APIs, such as <code>InspectLoader.is_package()</code>, to fill in any missing information on the spec.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="importlib.util.spec_from_file_location">
<code>importlib.util.spec_from_file_location(name, location, *, loader=None, submodule_search_locations=None)</code> </dt> <dd>
<p>A factory function for creating a <a class="reference internal" href="#importlib.machinery.ModuleSpec" title="importlib.machinery.ModuleSpec"><code>ModuleSpec</code></a> instance based on the path to a file. Missing information will be filled in on the spec by making use of loader APIs and by the implication that the module will be file-based.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>Accepts a <a class="reference internal" href="../glossary#term-path-like-object"><span class="xref std std-term">path-like object</span></a>.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="importlib.util.source_hash">
<code>importlib.util.source_hash(source_bytes)</code> </dt> <dd>
<p>Return the hash of <em>source_bytes</em> as bytes. A hash-based <code>.pyc</code> file embeds the <a class="reference internal" href="#importlib.util.source_hash" title="importlib.util.source_hash"><code>source_hash()</code></a> of the corresponding source file’s contents in its header.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="importlib.util._incompatible_extension_module_restrictions">
<code>importlib.util._incompatible_extension_module_restrictions(*, disable_check)</code> </dt> <dd>
<p>A context manager that can temporarily skip the compatibility check for extension modules. By default the check is enabled and will fail when a single-phase init module is imported in a subinterpreter. It will also fail for a multi-phase init module that doesn’t explicitly support a per-interpreter GIL, when imported in an interpreter with its own GIL.</p> <p>Note that this function is meant to accommodate an unusual case; one which is likely to eventually go away. There’s is a pretty good chance this is not what you were looking for.</p> <p>You can get the same effect as this function by implementing the basic interface of multi-phase init (<span class="target" id="index-26"></span><a class="pep reference external" href="https://peps.python.org/pep-0489/"><strong>PEP 489</strong></a>) and lying about support for multiple interpreters (or per-interpreter GIL).</p> <div class="admonition warning"> <p class="admonition-title">Warning</p> <p>Using this function to disable the check can lead to unexpected behavior and even crashes. It should only be used during extension module development.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12.</span></p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="importlib.util.LazyLoader">
<code>class importlib.util.LazyLoader(loader)</code> </dt> <dd>
<p>A class which postpones the execution of the loader of a module until the module has an attribute accessed.</p> <p>This class <strong>only</strong> works with loaders that define <a class="reference internal" href="#importlib.abc.Loader.exec_module" title="importlib.abc.Loader.exec_module"><code>exec_module()</code></a> as control over what module type is used for the module is required. For those same reasons, the loader’s <a class="reference internal" href="#importlib.abc.Loader.create_module" title="importlib.abc.Loader.create_module"><code>create_module()</code></a> method must return <code>None</code> or a type for which its <code>__class__</code> attribute can be mutated along with not using <a class="reference internal" href="../glossary#term-__slots__"><span class="xref std std-term">slots</span></a>. Finally, modules which substitute the object placed into <a class="reference internal" href="sys#sys.modules" title="sys.modules"><code>sys.modules</code></a> will not work as there is no way to properly replace the module references throughout the interpreter safely; <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> is raised if such a substitution is detected.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>For projects where startup time is critical, this class allows for potentially minimizing the cost of loading a module if it is never used. For projects where startup time is not essential then use of this class is <strong>heavily</strong> discouraged due to error messages created during loading being postponed and thus occurring out of context.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>Began calling <a class="reference internal" href="#importlib.abc.Loader.create_module" title="importlib.abc.Loader.create_module"><code>create_module()</code></a>, removing the compatibility warning for <a class="reference internal" href="#importlib.machinery.BuiltinImporter" title="importlib.machinery.BuiltinImporter"><code>importlib.machinery.BuiltinImporter</code></a> and <a class="reference internal" href="#importlib.machinery.ExtensionFileLoader" title="importlib.machinery.ExtensionFileLoader"><code>importlib.machinery.ExtensionFileLoader</code></a>.</p> </div> <dl class="py method"> <dt class="sig sig-object py" id="importlib.util.LazyLoader.factory">
<code>classmethod factory(loader)</code> </dt> <dd>
<p>A class method which returns a callable that creates a lazy loader. This is meant to be used in situations where the loader is passed by class instead of by instance.</p> <pre data-language="python">suffixes = importlib.machinery.SOURCE_SUFFIXES
loader = importlib.machinery.SourceFileLoader
lazy_loader = importlib.util.LazyLoader.factory(loader)
finder = importlib.machinery.FileFinder(path, (lazy_loader, suffixes))
</pre> </dd>
</dl> </dd>
</dl> </section> <section id="examples"> <span id="importlib-examples"></span><h2>Examples</h2> <section id="importing-programmatically"> <h3>Importing programmatically</h3> <p>To programmatically import a module, use <a class="reference internal" href="#importlib.import_module" title="importlib.import_module"><code>importlib.import_module()</code></a>.</p> <pre data-language="python">import importlib
itertools = importlib.import_module('itertools')
</pre> </section> <section id="checking-if-a-module-can-be-imported"> <h3>Checking if a module can be imported</h3> <p>If you need to find out if a module can be imported without actually doing the import, then you should use <a class="reference internal" href="#importlib.util.find_spec" title="importlib.util.find_spec"><code>importlib.util.find_spec()</code></a>.</p> <p>Note that if <code>name</code> is a submodule (contains a dot), <a class="reference internal" href="#importlib.util.find_spec" title="importlib.util.find_spec"><code>importlib.util.find_spec()</code></a> will import the parent module.</p> <pre data-language="python">import importlib.util
import sys
# For illustrative purposes.
name = 'itertools'
if name in sys.modules:
print(f"{name!r} already in sys.modules")
elif (spec := importlib.util.find_spec(name)) is not None:
# If you chose to perform the actual import ...
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
spec.loader.exec_module(module)
print(f"{name!r} has been imported")
else:
print(f"can't find the {name!r} module")
</pre> </section> <section id="importing-a-source-file-directly"> <h3>Importing a source file directly</h3> <p>To import a Python source file directly, use the following recipe:</p> <pre data-language="python">import importlib.util
import sys
# For illustrative purposes.
import tokenize
file_path = tokenize.__file__
module_name = tokenize.__name__
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
</pre> </section> <section id="implementing-lazy-imports"> <h3>Implementing lazy imports</h3> <p>The example below shows how to implement lazy imports:</p> <pre data-language="python">>>> import importlib.util
>>> import sys
>>> def lazy_import(name):
... spec = importlib.util.find_spec(name)
... loader = importlib.util.LazyLoader(spec.loader)
... spec.loader = loader
... module = importlib.util.module_from_spec(spec)
... sys.modules[name] = module
... loader.exec_module(module)
... return module
...
>>> lazy_typing = lazy_import("typing")
>>> #lazy_typing is a real module object,
>>> #but it is not loaded in memory yet.
>>> lazy_typing.TYPE_CHECKING
False
</pre> </section> <section id="setting-up-an-importer"> <h3>Setting up an importer</h3> <p>For deep customizations of import, you typically want to implement an <a class="reference internal" href="../glossary#term-importer"><span class="xref std std-term">importer</span></a>. This means managing both the <a class="reference internal" href="../glossary#term-finder"><span class="xref std std-term">finder</span></a> and <a class="reference internal" href="../glossary#term-loader"><span class="xref std std-term">loader</span></a> side of things. For finders there are two flavours to choose from depending on your needs: a <a class="reference internal" href="../glossary#term-meta-path-finder"><span class="xref std std-term">meta path finder</span></a> or a <a class="reference internal" href="../glossary#term-path-entry-finder"><span class="xref std std-term">path entry finder</span></a>. The former is what you would put on <a class="reference internal" href="sys#sys.meta_path" title="sys.meta_path"><code>sys.meta_path</code></a> while the latter is what you create using a <a class="reference internal" href="../glossary#term-path-entry-hook"><span class="xref std std-term">path entry hook</span></a> on <a class="reference internal" href="sys#sys.path_hooks" title="sys.path_hooks"><code>sys.path_hooks</code></a> which works with <a class="reference internal" href="sys#sys.path" title="sys.path"><code>sys.path</code></a> entries to potentially create a finder. This example will show you how to register your own importers so that import will use them (for creating an importer for yourself, read the documentation for the appropriate classes defined within this package):</p> <pre data-language="python">import importlib.machinery
import sys
# For illustrative purposes only.
SpamMetaPathFinder = importlib.machinery.PathFinder
SpamPathEntryFinder = importlib.machinery.FileFinder
loader_details = (importlib.machinery.SourceFileLoader,
importlib.machinery.SOURCE_SUFFIXES)
# Setting up a meta path finder.
# Make sure to put the finder in the proper location in the list in terms of
# priority.
sys.meta_path.append(SpamMetaPathFinder)
# Setting up a path entry finder.
# Make sure to put the path hook in the proper location in the list in terms
# of priority.
sys.path_hooks.append(SpamPathEntryFinder.path_hook(loader_details))
</pre> </section> <section id="approximating-importlib-import-module"> <h3>Approximating <a class="reference internal" href="#importlib.import_module" title="importlib.import_module"><code>importlib.import_module()</code></a>
</h3> <p>Import itself is implemented in Python code, making it possible to expose most of the import machinery through importlib. The following helps illustrate the various APIs that importlib exposes by providing an approximate implementation of <a class="reference internal" href="#importlib.import_module" title="importlib.import_module"><code>importlib.import_module()</code></a>:</p> <pre data-language="python">import importlib.util
import sys
def import_module(name, package=None):
"""An approximate implementation of import."""
absolute_name = importlib.util.resolve_name(name, package)
try:
return sys.modules[absolute_name]
except KeyError:
pass
path = None
if '.' in absolute_name:
parent_name, _, child_name = absolute_name.rpartition('.')
parent_module = import_module(parent_name)
path = parent_module.__spec__.submodule_search_locations
for finder in sys.meta_path:
spec = finder.find_spec(absolute_name, path)
if spec is not None:
break
else:
msg = f'No module named {absolute_name!r}'
raise ModuleNotFoundError(msg, name=absolute_name)
module = importlib.util.module_from_spec(spec)
sys.modules[absolute_name] = module
spec.loader.exec_module(module)
if path is not None:
setattr(parent_module, child_name, module)
return module
</pre> </section> </section> <div class="_attribution">
<p class="_attribution-p">
© 2001–2023 Python Software Foundation<br>Licensed under the PSF License.<br>
<a href="https://docs.python.org/3.12/library/importlib.html" class="_attribution-link">https://docs.python.org/3.12/library/importlib.html</a>
</p>
</div>
|