Repository navigation
Expand file tree
/
Copy pathimportlib.rst
More file actions
1561 lines (1073 loc) · 55.7 KB
/
Copy pathimportlib.rst
File metadata and controls
1561 lines (1073 loc) · 55.7 KB
Edit and raw actions
OlderNewer
1
:mod:`!importlib` --- The implementation of :keyword:`!import`
2
==============================================================
3
4
.. module:: importlib
5
:synopsis: The implementation of the import machinery.
6
7
.. versionadded:: 3.1
8
9
**Source code:** :source:`Lib/importlib/__init__.py`
10
11
--------------
12
13
14
Introduction
15
------------
16
17
The purpose of the :mod:`!importlib` package is three-fold.
18
19
One is to provide the
20
implementation of the :keyword:`import` statement (and thus, by extension, the
21
:func:`__import__` function) in Python source code. This provides an
22
implementation of :keyword:`!import` which is portable to any Python
23
interpreter. This also provides an implementation which is easier to
24
comprehend than one implemented in a programming language other than Python.
25
26
Two, the components to implement :keyword:`import` are exposed in this
27
package, making it easier for users to create their own custom objects (known
28
generically as an :term:`importer`) to participate in the import process.
29
30
Three, the package contains modules exposing additional functionality for
31
managing aspects of Python packages:
32
33
* :mod:`importlib.metadata` presents access to metadata from third-party
34
distributions.
35
* :mod:`importlib.resources` provides routines for accessing non-code
36
"resources" from Python packages.
37
38
.. seealso::
39
40
:ref:`import`
41
The language reference for the :keyword:`import` statement.
42
43
`Packages specification <https://www.python.org/doc/essays/packages/>`__
44
Original specification of packages. Some semantics have changed since
45
the writing of this document (e.g. redirecting based on ``None``
46
in :data:`sys.modules`).
47
48
The :func:`.__import__` function
49
The :keyword:`import` statement is syntactic sugar for this function.
50
51
:ref:`sys-path-init`
52
The initialization of :data:`sys.path`.
53
54
:pep:`235`
55
Import on Case-Insensitive Platforms
56
57
:pep:`263`
58
Defining Python Source Code Encodings
59
60
:pep:`302`
61
New Import Hooks
62
63
:pep:`328`
64
Imports: Multi-Line and Absolute/Relative
65
66
:pep:`366`
67
Main module explicit relative imports
68
69
:pep:`420`
70
Implicit namespace packages
71
72
:pep:`451`
73
A ModuleSpec Type for the Import System
74
75
:pep:`488`
76
Elimination of PYO files
77
78
:pep:`489`
79
Multi-phase extension module initialization
80
81
:pep:`552`
82
Deterministic pycs
83
84
:pep:`3120`
85
Using UTF-8 as the Default Source Encoding
86
87
:pep:`3147`
88
PYC Repository Directories
89
90
91
Functions
92
---------
93
94
.. function:: __import__(name, globals=None, locals=None, fromlist=(), level=0)
95
96
An implementation of the built-in :func:`__import__` function.
97
98
.. note::
99
Programmatic importing of modules should use :func:`import_module`
100
instead of this function.
101
102
.. function:: import_module(name, package=None)
103
104
Import a module. The *name* argument specifies what module to
105
import in absolute or relative terms
106
(e.g. either ``pkg.mod`` or ``..mod``). If the name is
107
specified in relative terms, then the *package* argument must be set to
108
the name of the package which is to act as the anchor for resolving the
109
package name (e.g. ``import_module('..mod', 'pkg.subpkg')`` will import
110
``pkg.mod``).
111
112
The :func:`import_module` function acts as a simplifying wrapper around
113
:func:`importlib.__import__`. This means all semantics of the function are
114
derived from :func:`importlib.__import__`. The most important difference
115
between these two functions is that :func:`import_module` returns the
116
specified package or module (e.g. ``pkg.mod``), while :func:`__import__`
117
returns the top-level package or module (e.g. ``pkg``).
118
119
If you are dynamically importing a module that was created since the
120
interpreter began execution (e.g., created a Python source file), you may
121
need to call :func:`invalidate_caches` in order for the new module to be
122
noticed by the import system.
123
124
If the module cannot be imported, :func:`import_module` will raise
125
:exc:`ImportError` or an appropriate subclass like
126
:exc:`ModuleNotFoundError`.
127
128
.. versionchanged:: 3.3
129
Parent packages are automatically imported.
130
131
.. function:: invalidate_caches()
132
133
Invalidate the internal caches of finders stored at
134
:data:`sys.meta_path`. If a finder implements ``invalidate_caches()`` then it
135
will be called to perform the invalidation. This function should be called
136
if any modules are created/installed while your program is running to
137
guarantee all finders will notice the new module's existence.
138
139
.. versionadded:: 3.3
140
141
.. versionchanged:: 3.10
142
Namespace packages created/installed in a different :data:`sys.path`
143
location after the same namespace was already imported are noticed.
144
145
.. function:: reload(module)
146
147
Reload a previously imported *module*. The argument must be a module object,
148
so it must have been successfully imported before. This is useful if you
149
have edited the module source file using an external editor and want to try
150
out the new version without leaving the Python interpreter. The return value
151
is the module object (which can be different if re-importing causes a
152
different object to be placed in :data:`sys.modules`).
153
154
When :func:`reload` is executed:
155
156
* Python module's code is recompiled and the module-level code re-executed,
157
defining a new set of objects which are bound to names in the module's
158
dictionary by reusing the :term:`loader` which originally loaded the
159
module. The ``init`` function of extension modules is not called a second
160
time.
161
162
* As with all other objects in Python the old objects are only reclaimed
163
after their reference counts drop to zero.
164
165
* The names in the module namespace are updated to point to any new or
166
changed objects.
167
168
* Other references to the old objects (such as names external to the module) are
169
not rebound to refer to the new objects and must be updated in each namespace
170
where they occur if that is desired.
171
172
There are a number of other caveats:
173
174
When a module is reloaded, its dictionary (containing the module's global
175
variables) is retained. Redefinitions of names will override the old
176
definitions, so this is generally not a problem. If the new version of a
177
module does not define a name that was defined by the old version, the old
178
definition remains. This feature can be used to the module's advantage if it
179
maintains a global table or cache of objects --- with a :keyword:`try`
180
statement it can test for the table's presence and skip its initialization if
181
desired::
182
183
try:
184
cache
185
except NameError:
186
cache = {}
187
188
It is generally not very useful to reload built-in or dynamically loaded
189
modules. Reloading :mod:`sys`, :mod:`__main__`, :mod:`builtins` and other
190
key modules is not recommended. In many cases extension modules are not
191
designed to be initialized more than once, and may fail in arbitrary ways
192
when reloaded.
193
194
If a module imports objects from another module using :keyword:`from` ...
195
:keyword:`import` ..., calling :func:`reload` for the other module does not
196
redefine the objects imported from it --- one way around this is to
197
re-execute the :keyword:`!from` statement, another is to use :keyword:`!import`
198
and qualified names (*module.name*) instead.
199
200
If a module instantiates instances of a class, reloading the module that
201
defines the class does not affect the method definitions of the instances ---
202
they continue to use the old class definition. The same is true for derived
203
classes.
204
205
.. versionadded:: 3.4
206
.. versionchanged:: 3.7
207
:exc:`ModuleNotFoundError` is raised when the module being reloaded lacks
208
a :class:`~importlib.machinery.ModuleSpec`.
209
210
.. warning::
211
This function is not thread-safe. Calling it from multiple threads can result
212
in unexpected behavior. It's recommended to use the :class:`threading.Lock`
213
or other synchronization primitives for thread-safe module reloading.
214
215
:mod:`!importlib.abc` -- Abstract base classes related to import
216
----------------------------------------------------------------
217
218
.. module:: importlib.abc
219
:synopsis: Abstract base classes related to import
220
221
**Source code:** :source:`Lib/importlib/abc.py`
222
223
--------------
224
225
226
The :mod:`!importlib.abc` module contains all of the core abstract base classes
227
used by :keyword:`import`. Some subclasses of the core abstract base classes
228
are also provided to help in implementing the core ABCs.
229
230
ABC hierarchy::
231
232
object
233
+-- MetaPathFinder
234
+-- PathEntryFinder
235
+-- Loader
236
+-- ResourceLoader --------+
237
+-- InspectLoader |
238
+-- ExecutionLoader --+
239
+-- FileLoader
240
+-- SourceLoader
241
242
243
.. class:: MetaPathFinder
244
245
An abstract base class representing a :term:`meta path finder`.
246
247
.. versionadded:: 3.3
248
249
.. versionchanged:: 3.10
250
No longer a subclass of :class:`!Finder`.
251
252
.. method:: find_spec(fullname, path,>
253
254
An abstract method for finding a :term:`spec <module spec>` for
255
the specified module. If this is a top-level import, *path* will
256
be ``None``. Otherwise, this is a search for a subpackage or
257
module and *path* will be the value of :attr:`~module.__path__` from the
258
parent package. If a spec cannot be found, ``None`` is returned.
259
When passed in, ``target`` is a module object that the finder may
260
use to make a more educated guess about what spec to return.
261
:func:`importlib.util.spec_from_loader` may be useful for implementing
262
concrete ``MetaPathFinders``.
263
264
.. versionadded:: 3.4
265
266
.. method:: invalidate_caches()
267
268
An optional method which, when called, should invalidate any internal
269
cache used by the finder. Used by :func:`importlib.invalidate_caches`
270
when invalidating the caches of all finders on :data:`sys.meta_path`.
271
272
.. versionchanged:: 3.4
273
Returns ``None`` when called instead of :data:`NotImplemented`.
274
275
.. method:: discover(parent=None)
276
277
An optional method which searches for possible specs with given *parent*
278
module spec. If *parent* is *None*, :meth:`MetaPathFinder.discover` will
279
search for top-level modules.
280
281
Returns an iterable of possible specs.
282
283
Raises :exc:`ValueError` if *parent* is not a package module.
284
285
.. warning::
286
This method can potentially yield a very large number of objects, and
287
it may carry out IO operations when computing these values.
288
289
Because of this, it will generally be desirable to compute the result
290
values on-the-fly, as they are needed. As such, the returned object is
291
only guaranteed to be an :class:`iterable <collections.abc.Iterable>`,
292
instead of a :class:`list` or other
293
:class:`collection <collections.abc.Collection>` type.
294
295
.. versionadded:: 3.15
296
297
298
.. class:: PathEntryFinder
299
300
An abstract base class representing a :term:`path entry finder`. Though
301
it bears some similarities to :class:`MetaPathFinder`, ``PathEntryFinder``
302
is meant for use only within the path-based import subsystem provided
303
by :class:`importlib.machinery.PathFinder`.
304
305
.. versionadded:: 3.3
306
307
.. versionchanged:: 3.10
308
No longer a subclass of :class:`!Finder`.
309
310
.. method:: find_spec(fullname,>
311
312
An abstract method for finding a :term:`spec <module spec>` for
313
the specified module. The finder will search for the module only
314
within the :term:`path entry` to which it is assigned. If a spec
315
cannot be found, ``None`` is returned. When passed in, ``target``
316
is a module object that the finder may use to make a more educated
317
guess about what spec to return. :func:`importlib.util.spec_from_loader`
318
may be useful for implementing concrete ``PathEntryFinders``.
319
320
.. versionadded:: 3.4
321
322
.. method:: invalidate_caches()
323
324
An optional method which, when called, should invalidate any internal
325
cache used by the finder. Used by
326
:meth:`importlib.machinery.PathFinder.invalidate_caches`
327
when invalidating the caches of all cached finders.
328
329
.. method:: discover(parent=None)
330
331
An optional method which searches for possible specs with given *parent*
332
module spec. If *parent* is *None*, :meth:`PathEntryFinder.discover` will
333
search for top-level modules.
334
335
Returns an iterable of possible specs.
336
337
Raises :exc:`ValueError` if *parent* is not a package module.
338
339
.. warning::
340
This method can potentially yield a very large number of objects, and
341
it may carry out IO operations when computing these values.
342
343
Because of this, it will generally be desirable to compute the result
344
values on-the-fly, as they are needed. As such, the returned object is
345
only guaranteed to be an :class:`iterable <collections.abc.Iterable>`,
346
instead of a :class:`list` or other
347
:class:`collection <collections.abc.Collection>` type.
348
349
.. versionadded:: 3.15
350
351
352
.. class:: Loader
353
354
An abstract base class for a :term:`loader`.
355
See :pep:`302` for the exact definition for a loader.
356
357
Loaders that wish to support resource reading should implement a
358
:meth:`!get_resource_reader` method as specified by
359
:class:`importlib.resources.abc.ResourceReader`.
360
361
.. versionchanged:: 3.7
362
Introduced the optional :meth:`!get_resource_reader` method.
363
364
.. versionchanged:: 3.15
365
Removed the ``load_module()`` method.
366
367
.. method:: create_module(spec)
368
369
A method that returns the module object to use when
370
importing a module. This method may return ``None``,
371
indicating that default module creation semantics should take place.
372
373
.. versionadded:: 3.4
374
375
.. versionchanged:: 3.6
376
This method is no longer optional when
377
:meth:`exec_module` is defined.
378
379
.. method:: exec_module(module)
380
381
An abstract method that executes the module in its own namespace
382
when a module is imported or reloaded. The module should already
383
be initialized when :meth:`exec_module` is called. When this method exists,
384
:meth:`create_module` must be defined.
385
386
.. versionadded:: 3.4
387
388
.. versionchanged:: 3.6
389
:meth:`create_module` must also be defined.
390
391
392
.. class:: ResourceLoader
393
394
*Superseded by TraversableResources*
395
396
An abstract base class for a :term:`loader` which implements the optional
397
:pep:`302` protocol for loading arbitrary resources from the storage
398
back-end.
399
400
.. deprecated:: 3.7
401
This ABC is deprecated in favour of supporting resource loading
402
through :class:`importlib.resources.abc.TraversableResources`.
403
This class exists for backwards compatibility only with other ABCs in
404
this module.
405
406
.. method:: get_data(path)
407
:abstractmethod:
408
409
An abstract method to return the bytes for the data located at *path*.
410
Loaders that have a file-like storage back-end
411
that allows storing arbitrary data
412
can implement this abstract method to give direct access
413
to the data stored. :exc:`OSError` is to be raised if the *path* cannot
414
be found. The *path* is expected to be constructed using a module's
415
:attr:`~module.__file__` attribute or an item from a package's
416
:attr:`~module.__path__`.
417
418
.. versionchanged:: 3.4
419
Raises :exc:`OSError` instead of :exc:`NotImplementedError`.
420
421
422
.. class:: InspectLoader
423
424
An abstract base class for a :term:`loader` which implements the optional
425
:pep:`302` protocol for loaders that inspect modules.
426
427
.. method:: get_code(fullname)
428
429
Return the code object for a module, or ``None`` if the module does not
430
have a code object (as would be the case, for example, for a built-in
431
module). Raise an :exc:`ImportError` if loader cannot find the
432
requested module.
433
434
.. note::
435
While the method has a default implementation, it is suggested that
436
it be overridden if possible for performance.
437
438
.. index::
439
single: universal newlines; importlib.abc.InspectLoader.get_source method
440
441
.. versionchanged:: 3.4
442
No longer abstract and a concrete implementation is provided.
443
444
.. method:: get_source(fullname)
445
:abstractmethod:
446
447
An abstract method to return the source of a module. It is returned as
448
a text string using :term:`universal newlines`, translating all
449
recognized line separators into ``'\n'`` characters. Returns ``None``
450
if no source is available (e.g. a built-in module). Raises
451
:exc:`ImportError` if the loader cannot find the module specified.
452
453
.. versionchanged:: 3.4
454
Raises :exc:`ImportError` instead of :exc:`NotImplementedError`.
455
456
.. method:: is_package(fullname)
457
458
An optional method to return a true value if the module is a package, a
459
false value otherwise. :exc:`ImportError` is raised if the
460
:term:`loader` cannot find the module.
461
462
.. versionchanged:: 3.4
463
Raises :exc:`ImportError` instead of :exc:`NotImplementedError`.
464
465
.. staticmethod:: source_to_code(data, path='<string>', fullname=None)
466
467
Create a code object from Python source.
468
469
The *data* argument can be whatever the :func:`compile` function
470
supports (i.e. string or bytes). The *path* argument should be
471
the "path" to where the source code originated from, which can be an
472
abstract concept (e.g. location in a zip file).
473
474
With the subsequent code object one can execute it in a module by
475
running ``exec(code, module.__dict__)``.
476
477
The optional argument *fullname* specifies the module name.
478
It is needed to unambiguous :ref:`filter <warning-filter>` syntax
479
warnings by module name.
480
481
.. versionadded:: 3.4
482
483
.. versionchanged:: 3.5
484
Made the method static.
485
486
.. versionadded:: 3.15
487
Added the *fullname* parameter.
488
489
490
.. method:: exec_module(module)
491
492
Implementation of :meth:`Loader.exec_module`.
493
494
.. versionadded:: 3.4
495
496
497
.. class:: ExecutionLoader
498
499
An abstract base class which inherits from :class:`InspectLoader` that,
500
when implemented, helps a module to be executed as a script. The ABC
501
represents an optional :pep:`302` protocol.
502
503
.. method:: get_filename(fullname)
504
:abstractmethod:
505
506
An abstract method that is to return the value of
507
:attr:`~module.__file__` for the specified module. If no path is
508
available, :exc:`ImportError` is raised.
509
510
If source code is available, then the method should return the path to
511
the source file, regardless of whether a bytecode was used to load the
512
module.
513
514
.. versionchanged:: 3.4
515
Raises :exc:`ImportError` instead of :exc:`NotImplementedError`.
516
517
518
.. class:: FileLoader(fullname, path)
519
520
An abstract base class which inherits from :class:`ResourceLoader` and
521
:class:`ExecutionLoader`, providing concrete implementations of
522
:meth:`ResourceLoader.get_data` and :meth:`ExecutionLoader.get_filename`.
523
524
The *fullname* argument is a fully resolved name of the module the loader is
525
to handle. The *path* argument is the path to the file for the module.
526
527
.. versionadded:: 3.3
528
529
.. versionchanged:: 3.15
530
Removed the ``load_module()`` method.
531
532
.. attribute:: name
533
534
The name of the module the loader can handle.
535
536
.. attribute:: path
537
538
Path to the file of the module.
539
540
.. method:: get_filename(fullname)
541
:abstractmethod:
542
543
Returns :attr:`path`.
544
545
.. method:: get_data(path)
546
:abstractmethod:
547
548
Reads *path* as a binary file and returns the bytes from it.
549
550
551
.. class:: SourceLoader
552
553
An abstract base class for implementing source (and optionally bytecode)
554
file loading. The class inherits from both :class:`ResourceLoader` and
555
:class:`ExecutionLoader`, requiring the implementation of:
556
557
* :meth:`ResourceLoader.get_data`
558
* :meth:`ExecutionLoader.get_filename`
559
Should only return the path to the source file; sourceless
560
loading is not supported.
561
562
The abstract methods defined by this class are to add optional bytecode
563
file support. Not implementing these optional methods (or causing them to
564
raise :exc:`NotImplementedError`) causes the loader to
565
only work with source code. Implementing the methods allows the loader to
566
work with source *and* bytecode files; it does not allow for *sourceless*
567
loading where only bytecode is provided. Bytecode files are an
568
optimization to speed up loading by removing the parsing step of Python's
569
compiler, and so no bytecode-specific API is exposed.
570
571
.. versionchanged:: 3.15
572
Removed the ``load_module()`` method.
573
574
.. method:: path_stats(path)
575
576
Optional abstract method which returns a :class:`dict` containing
577
metadata about the specified path. Supported dictionary keys are:
578
579
- ``'mtime'`` (mandatory): an integer or floating-point number
580
representing the modification time of the source code;
581
- ``'size'`` (optional): the size in bytes of the source code.
582
583
Any other keys in the dictionary are ignored, to allow for future
584
extensions. If the path cannot be handled, :exc:`OSError` is raised.
585
586
.. versionadded:: 3.3
587
588
.. versionchanged:: 3.4
589
Raise :exc:`OSError` instead of :exc:`NotImplementedError`.
590
591
.. method:: path_mtime(path)
592
593
Optional abstract method which returns the modification time for the
594
specified path.
595
596
.. deprecated:: 3.3
597
This method is deprecated in favour of :meth:`path_stats`. You don't
598
have to implement it, but it is still available for compatibility
599
purposes. Raise :exc:`OSError` if the path cannot be handled.
600
601
.. versionchanged:: 3.4
602
Raise :exc:`OSError` instead of :exc:`NotImplementedError`.
603
604
.. method:: set_data(path, data)
605
606
Optional abstract method which writes the specified bytes to a file
607
path. Any intermediate directories which do not exist are to be created
608
automatically.
609
610
When writing to the path fails because the path is read-only
611
(:const:`errno.EACCES`/:exc:`PermissionError`), do not propagate the
612
exception.
613
614
.. versionchanged:: 3.4
615
No longer raises :exc:`NotImplementedError` when called.
616
617
.. method:: get_code(fullname)
618
619
Concrete implementation of :meth:`InspectLoader.get_code`.
620
621
.. method:: exec_module(module)
622
623
Concrete implementation of :meth:`Loader.exec_module`.
624
625
.. versionadded:: 3.4
626
627
.. method:: get_source(fullname)
628
629
Concrete implementation of :meth:`InspectLoader.get_source`.
630
631
.. method:: is_package(fullname)
632
633
Concrete implementation of :meth:`InspectLoader.is_package`. A module
634
is determined to be a package if its file path (as provided by
635
:meth:`ExecutionLoader.get_filename`) is a file named
636
``__init__`` when the file extension is removed **and** the module name
637
itself does not end in ``__init__``.
638
639
640
:mod:`!importlib.machinery` -- Importers and path hooks
641
-------------------------------------------------------
642
643
.. module:: importlib.machinery
644
:synopsis: Importers and path hooks
645
646
**Source code:** :source:`Lib/importlib/machinery.py`
647
648
--------------
649
650
This module contains the various objects that help :keyword:`import`
651
find and load modules.
652
653
.. data:: SOURCE_SUFFIXES
654
655
A list of strings representing the recognized file suffixes for source
656
modules.
657
658
.. versionadded:: 3.3
659
660
.. data:: DEBUG_BYTECODE_SUFFIXES
661
662
A list of strings representing the file suffixes for non-optimized bytecode
663
modules.
664
665
.. versionadded:: 3.3
666
667
.. deprecated:: 3.5
668
Use :const:`BYTECODE_SUFFIXES` instead.
669
670
.. data:: OPTIMIZED_BYTECODE_SUFFIXES
671
672
A list of strings representing the file suffixes for optimized bytecode
673
modules.
674
675
.. versionadded:: 3.3
676
677
.. deprecated:: 3.5
678
Use :const:`BYTECODE_SUFFIXES` instead.
679
680
.. data:: BYTECODE_SUFFIXES
681
682
A list of strings representing the recognized file suffixes for bytecode
683
modules (including the leading dot).
684
685
.. versionadded:: 3.3
686
687
.. versionchanged:: 3.5
688
The value is no longer dependent on ``__debug__``.
689
690
.. data:: EXTENSION_SUFFIXES
691
692
A list of strings representing the recognized file suffixes for
693
extension modules.
694
695
.. versionadded:: 3.3
696
697
.. function:: all_suffixes()
698
699
Returns a combined list of strings representing all file suffixes for
700
modules recognized by the standard import machinery. This is a
701
helper for code which simply needs to know if a filesystem path
702
potentially refers to a module without needing any details on the kind
703
of module (for example, :func:`inspect.getmodulename`).
704
705
.. versionadded:: 3.3
706
707
708
.. class:: BuiltinImporter
709
710
An :term:`importer` for built-in modules. All known built-in modules are
711
listed in :data:`sys.builtin_module_names`. This class implements the
712
:class:`importlib.abc.MetaPathFinder` and
713
:class:`importlib.abc.InspectLoader` ABCs.
714
715
Only class methods are defined by this class to alleviate the need for
716
instantiation.
717
718
.. versionchanged:: 3.5
719
As part of :pep:`489`, the builtin importer now implements
720
:meth:`Loader.create_module <importlib.abc.Loader.create_module>`
721
and :meth:`Loader.exec_module <importlib.abc.Loader.exec_module>`
722
723
724
.. class:: FrozenImporter
725
726
An :term:`importer` for frozen modules. This class implements the
727
:class:`importlib.abc.MetaPathFinder` and
728
:class:`importlib.abc.InspectLoader` ABCs.
729
730
Only class methods are defined by this class to alleviate the need for
731
instantiation.
732
733
.. versionchanged:: 3.4
734
Gained :meth:`~importlib.abc.Loader.create_module` and
735
:meth:`~importlib.abc.Loader.exec_module`
736
methods.
737
738
739
.. class:: WindowsRegistryFinder
740
741
:term:`Finder <finder>` for modules declared in the Windows registry. This class
742
implements the :class:`importlib.abc.MetaPathFinder` ABC.
743
744
Only class methods are defined by this class to alleviate the need for
745
instantiation.
746
747
.. versionadded:: 3.3
748
749
.. deprecated:: 3.6
750
Use :mod:`site` configuration instead. Future versions of Python may
751
not enable this finder by default.
752
753
754
.. class:: PathFinder
755
756
A :term:`Finder <finder>` for :data:`sys.path` and package ``__path__`` attributes.
757
This class implements the :class:`importlib.abc.MetaPathFinder` ABC.
758
759
Only class methods are defined by this class to alleviate the need for
760
instantiation.
761
762
.. classmethod:: find_spec(fullname, path=None,>
763
764
Class method that attempts to find a :term:`spec <module spec>`
765
for the module specified by *fullname* on :data:`sys.path` or, if
766
defined, on *path*. For each path entry that is searched,
767
:data:`sys.path_importer_cache` is checked. If a non-false object
768
is found then it is used as the :term:`path entry finder` to look
769
for the module being searched for. If no entry is found in
770
:data:`sys.path_importer_cache`, then :data:`sys.path_hooks` is
771
searched for a finder for the path entry and, if found, is stored
772
in :data:`sys.path_importer_cache` along with being queried about
773
the module. If no finder is ever found then ``None`` is both
774
stored in the cache and returned.
775
776
.. versionadded:: 3.4
777
778
.. versionchanged:: 3.5
779
If the current working directory -- represented by an empty string --
780
is no longer valid then ``None`` is returned but no value is cached
781
in :data:`sys.path_importer_cache`.
782
783
.. classmethod:: invalidate_caches()
784
785
Calls :meth:`importlib.abc.PathEntryFinder.invalidate_caches` on all
786
finders stored in :data:`sys.path_importer_cache` that define the method.
787
Otherwise entries in :data:`sys.path_importer_cache` set to ``None`` are
788
deleted.
789
790
.. versionchanged:: 3.7
791
Entries of ``None`` in :data:`sys.path_importer_cache` are deleted.
792
793
.. versionchanged:: 3.4
794
Calls objects in :data:`sys.path_hooks` with the current working
795
directory for ``''`` (i.e. the empty string).
796
797
798
.. class:: FileFinder(path, *loader_details)
799
800
A concrete implementation of :class:`importlib.abc.PathEntryFinder` which
801
caches results from the file system.
802
803
The *path* argument is the directory for which the finder is in charge of
804
searching.
805
806
The *loader_details* argument is a variable number of 2-item tuples each
807
containing a loader and a sequence of file suffixes the loader recognizes.
808
The loaders are expected to be callables which accept two arguments of
809
the module's name and the path to the file found.
810
811
The finder will cache the directory contents as necessary, making stat calls
812
for each module search to verify the cache is not outdated. Because cache
813
staleness relies upon the granularity of the operating system's state
814
information of the file system, there is a potential race condition of
815
searching for a module, creating a new file, and then searching for the
816
module the new file represents. If the operations happen fast enough to fit
817
within the granularity of stat calls, then the module search will fail. To
818
prevent this from happening, when you create a module dynamically, make sure
819
to call :func:`importlib.invalidate_caches`.
820
821
.. versionadded:: 3.3
822
823
.. attribute:: path
824
825
The path the finder will search in.
826
827
.. method:: find_spec(fullname,>
828
829
Attempt to find the spec to handle *fullname* within :attr:`path`.
830
831
.. versionadded:: 3.4
832
833
.. method:: invalidate_caches()
834
835
Clear out the internal cache.
836
837
.. classmethod:: path_hook(*loader_details)
838
839
A class method which returns a closure for use on :data:`sys.path_hooks`.
840
An instance of :class:`FileFinder` is returned by the closure using the
841
path argument given to the closure directly and *loader_details*
842
indirectly.
843
844
If the argument to the closure is not an existing directory,
845
:exc:`ImportError` is raised.
846
847
848
.. class:: NamespacePath(name, path, path_finder)
849
850
Represents a :term:`namespace package`'s path (:attr:`module.__path__`).
851
852
When its ``__path__`` value is accessed it will be recomputed if necessary.
853
This keeps it in-sync with the global state (:attr:`sys.modules`).
854
855
The *name* argument is the name of the namespace module.
856
857
The *path* argument is the initial path value.
858
859
The *path_finder* argument is the callable used to recompute the path value.
860
The callable has the same signature as :meth:`importlib.abc.MetaPathFinder.find_spec`.
861
862
When the parent's :attr:`module.__path__` attribute is updated, the path
863
value is recomputed.
864
865
If the parent module is missing from :data:`sys.modules`, then
866
:exc:`ModuleNotFoundError` will be raised.
867
868
For top-level modules, the parent module's path is :data:`sys.path`.
869
870
.. note::
871
872
:meth:`PathFinder.invalidate_caches` invalidates :class:`NamespacePath`,
873
forcing the path value to be recomputed next time it is accessed.
874
875
.. versionadded:: 3.15
876
877
878
.. class:: SourceFileLoader(fullname, path)
879
880
A concrete implementation of :class:`importlib.abc.SourceLoader` by
881
subclassing :class:`importlib.abc.FileLoader` and providing some concrete
882
implementations of other methods.
883
884
.. versionadded:: 3.3
885
886
.. versionchanged:: 3.15
887
Removed the ``load_module()`` method.
888
889
.. attribute:: name
890
891
The name of the module that this loader will handle.
892
893
.. attribute:: path
894
895
The path to the source file.
896
897
.. method:: is_package(fullname)
898
899
Return ``True`` if :attr:`path` appears to be for a package.
900
901
.. method:: path_stats(path)
902
903
Concrete implementation of :meth:`importlib.abc.SourceLoader.path_stats`.
904
905
.. method:: set_data(path, data)
906
907
Concrete implementation of :meth:`importlib.abc.SourceLoader.set_data`.
908
909
910
.. class:: SourcelessFileLoader(fullname, path)
911
912
A concrete implementation of :class:`importlib.abc.FileLoader` which can
913
import bytecode files (i.e. no source code files exist).
914
915
Please note that direct use of bytecode files (and thus not source code
916
files) inhibits your modules from being usable by all Python
917
implementations or new versions of Python which change the bytecode
918
format.
919
920
.. versionadded:: 3.3
921
922
.. versionchanged:: 3.15
923
Removed the ``load_module()`` method.
924
925
.. attribute:: name
926
927
The name of the module the loader will handle.
928
929
.. attribute:: path
930
931
The path to the bytecode file.
932
933
.. method:: is_package(fullname)
934
935
Determines if the module is a package based on :attr:`path`.
936
937
.. method:: get_code(fullname)
938
939
Returns the code object for :attr:`name` created from :attr:`path`.
940
941
.. method:: get_source(fullname)
942
943
Returns ``None`` as bytecode files have no source when this loader is
944
used.
945
946
947
.. class:: ExtensionFileLoader(fullname, path)
948
949
A concrete implementation of :class:`importlib.abc.ExecutionLoader` for
950
extension modules.
951
952
The *fullname* argument specifies the name of the module the loader is to
953
support. The *path* argument is the path to the extension module's file.
954
955
Note that, by default, importing an extension module will fail
956
in subinterpreters if it doesn't implement multi-phase init
957
(see :pep:`489`), even if it would otherwise import successfully.
958
959
.. versionadded:: 3.3
960
961
.. versionchanged:: 3.12
962
Multi-phase init is now required for use in subinterpreters.
963
964
.. attribute:: name
965
966
Name of the module the loader supports.
967
968
.. attribute:: path
969
970
Path to the extension module.
971
972
.. method:: create_module(spec)
973
974
Creates the module object from the given specification in accordance
975
with :pep:`489`.
976
977
.. versionadded:: 3.5
978
979
.. method:: exec_module(module)
980
981
Initializes the given module object in accordance with :pep:`489`.
982
983
.. versionadded:: 3.5
984
985
.. method:: is_package(fullname)
986
987
Returns ``True`` if the file path points to a package's ``__init__``
988
module based on :const:`EXTENSION_SUFFIXES`.
989
990
.. method:: get_code(fullname)
991
992
Returns ``None`` as extension modules lack a code object.
993
994
.. method:: get_source(fullname)
995
996
Returns ``None`` as extension modules do not have source code.
997
998
.. method:: get_filename(fullname)
999
1000
Returns :attr:`path`.