• Home
  • Raw
  • Download

Lines Matching +full:is +full:- +full:module

1 :mod:`!importlib` --- The implementation of :keyword:`!import`
4 .. module:: importlib
14 --------------
18 ------------
20 The purpose of the :mod:`importlib` package is three-fold.
22 One is to provide the
25 implementation of :keyword:`!import` which is portable to any Python
26 interpreter. This also provides an implementation which is easier to
36 * :mod:`importlib.metadata` presents access to metadata from third-party
38 * :mod:`importlib.resources` provides routines for accessing non-code
52 The :keyword:`import` statement is syntactic sugar for this function.
54 :ref:`sys-path-init`
58 Import on Case-Insensitive Platforms
67 Imports: Multi-Line and Absolute/Relative
70 Main module explicit relative imports
82 Multi-phase extension module initialization
88 Using UTF-8 as the Default Source Encoding
95 ---------
99 An implementation of the built-in :func:`__import__` function.
107 Import a module. The *name* argument specifies what module to
109 (e.g. either ``pkg.mod`` or ``..mod``). If the name is
111 the name of the package which is to act as the anchor for resolving the
118 between these two functions is that :func:`import_module` returns the
119 specified package or module (e.g. ``pkg.mod``), while :func:`__import__`
120 returns the top-level package or module (e.g. ``pkg``).
122 If you are dynamically importing a module that was created since the
124 need to call :func:`invalidate_caches` in order for the new module to be
132 Find the loader for a module, optionally within the specified *path*. If the
133 module is in :attr:`sys.modules`, then ``sys.modules[name].__loader__`` is
134 returned (unless the loader would be ``None`` or is not set, in which case
135 :exc:`ValueError` is raised). Otherwise a search using :attr:`sys.meta_path`
136 is done. ``None`` is returned if no loader is found.
146 If ``__loader__`` is not set, raise :exc:`ValueError`, just like when the
147 attribute is set to ``None``.
157 if any modules are created/installed while your program is running to
158 guarantee all finders will notice the new module's existence.
166 .. function:: reload(module)
168 Reload a previously imported *module*. The argument must be a module object,
169 so it must have been successfully imported before. This is useful if you
170 have edited the module source file using an external editor and want to try
172 is the module object (which can be different if re-importing causes a
175 When :func:`reload` is executed:
177 * Python module's code is recompiled and the module-level code re-executed,
178 defining a new set of objects which are bound to names in the module's
180 module. The ``init`` function of extension modules is not called a second
186 * The names in the module namespace are updated to point to any new or
189 * Other references to the old objects (such as names external to the module) are
191 where they occur if that is desired.
195 When a module is reloaded, its dictionary (containing the module's global
196 variables) is retained. Redefinitions of names will override the old
197 definitions, so this is generally not a problem. If the new version of a
198 module does not define a name that was defined by the old version, the old
199 definition remains. This feature can be used to the module's advantage if it
200 maintains a global table or cache of objects --- with a :keyword:`try`
209 It is generally not very useful to reload built-in or dynamically loaded
211 key modules is not recommended. In many cases extension modules are not
215 If a module imports objects from another module using :keyword:`from` ...
216 :keyword:`import` ..., calling :func:`reload` for the other module does not
217 redefine the objects imported from it --- one way around this is to
218 re-execute the :keyword:`!from` statement, another is to use :keyword:`!import`
219 and qualified names (*module.name*) instead.
221 If a module instantiates instances of a class, reloading the module that
222 defines the class does not affect the method definitions of the instances ---
223 they continue to use the old class definition. The same is true for derived
228 :exc:`ModuleNotFoundError` is raised when the module being reloaded lacks
232 :mod:`importlib.abc` -- Abstract base classes related to import
233 ---------------------------------------------------------------
235 .. module:: importlib.abc
240 --------------
243 The :mod:`importlib.abc` module contains all of the core abstract base classes
250 +-- Finder (deprecated)
251 +-- MetaPathFinder
252 +-- PathEntryFinder
253 +-- Loader
254 +-- ResourceLoader --------+
255 +-- InspectLoader |
256 +-- ExecutionLoader --+
257 +-- FileLoader
258 +-- SourceLoader
271 module. Originally specified in :pep:`302`, this method was meant
272 for use in :data:`sys.meta_path` and in the path-based import subsystem.
294 An abstract method for finding a :term:`spec <module spec>` for
295 the specified module. If this is a top-level import, *path* will
296 be ``None``. Otherwise, this is a search for a subpackage or
297 module and *path* will be the value of :attr:`__path__` from the
298 parent package. If a spec cannot be found, ``None`` is returned.
299 When passed in, ``target`` is a module object that the finder may
309 module. If this is a top-level import, *path* will be ``None``.
310 Otherwise, this is a search for a subpackage or module and *path*
312 package. If a loader cannot be found, ``None`` is returned.
314 If :meth:`find_spec` is defined, backwards-compatible functionality is
339 is meant for use only within the path-based import subsystem provided
349 An abstract method for finding a :term:`spec <module spec>` for
350 the specified module. The finder will search for the module only
351 within the :term:`path entry` to which it is assigned. If a spec
352 cannot be found, ``None`` is returned. When passed in, ``target``
353 is a module object that the finder may use to make a more educated
362 module. Returns a 2-tuple of ``(loader, portion)`` where ``portion``
363 is a sequence of file system locations contributing to part of a namespace
367 is not part of a namespace package. If ``loader`` is ``None`` and
368 ``portion`` is the empty list then no loader or location for a namespace
369 package were found (i.e. failure to find anything for the module).
371 If :meth:`find_spec` is defined then backwards-compatible functionality is
383 A concrete implementation of :meth:`Finder.find_module` which is
411 A method that returns the module object to use when
412 importing a module. This method may return ``None``,
413 indicating that default module creation semantics should take place.
418 This method is no longer optional when
419 :meth:`exec_module` is defined.
421 .. method:: exec_module(module)
423 An abstract method that executes the module in its own namespace
424 when a module is imported or reloaded. The module should already
425 be initialized when :meth:`exec_module` is called. When this method exists,
435 A legacy method for loading a module. If the module cannot be
436 loaded, :exc:`ImportError` is raised, otherwise the loaded module is
439 If the requested module already exists in :data:`sys.modules`, that
440 module should be used and reloaded.
441 Otherwise the loader should create a new module and insert it into
443 from the import. If the loader inserted a module and the load fails, it
448 The loader should set several attributes on the module
449 (note that some of these attributes can change when a module is
452 - :attr:`__name__`
453 The module's fully qualified name.
454 It is ``'__main__'`` for an executed module.
456 - :attr:`__file__`
457 The location the :term:`loader` used to load the module.
458 For example, for modules loaded from a .py file this is the filename.
459 It is not set on all modules (e.g. built-in modules).
461 - :attr:`__cached__`
462 The filename of a compiled version of the module's code.
463 It is not set on all modules (e.g. built-in modules).
465 - :attr:`__path__`
467 Most of the time this is a single directory.
470 It is not set on non-package modules so it can be used
471 as an indicator that the module is a package.
473 - :attr:`__package__`
474 The fully qualified name of the package the module is in (or the
475 empty string for a top-level module).
476 If the module is a package then this is the same as :attr:`__name__`.
478 - :attr:`__loader__`
479 The :term:`loader` used to load the module.
481 When :meth:`exec_module` is available then backwards-compatible
482 functionality is provided.
487 :meth:`exec_module` is available.
490 The recommended API for loading a module is :meth:`exec_module`
494 :meth:`exec_module` is implemented.
496 .. method:: module_repr(module)
499 module's representation, as a string. The module type's default
515 back-end.
518 This ABC is deprecated in favour of supporting resource loading
524 Loaders that have a file-like storage back-end
527 to the data stored. :exc:`OSError` is to be raised if the *path* cannot
528 be found. The *path* is expected to be constructed using a module's
542 Return the code object for a module, or ``None`` if the module does not
543 have a code object (as would be the case, for example, for a built-in
544 module). Raise an :exc:`ImportError` if loader cannot find the
545 requested module.
548 While the method has a default implementation, it is suggested that
555 No longer abstract and a concrete implementation is provided.
559 An abstract method to return the source of a module. It is returned as
562 if no source is available (e.g. a built-in module). Raises
563 :exc:`ImportError` if the loader cannot find the module specified.
570 An optional method to return a true value if the module is a package, a
571 false value otherwise. :exc:`ImportError` is raised if the
572 :term:`loader` cannot find the module.
586 With the subsequent code object one can execute it in a module by
587 running ``exec(code, module.__dict__)``.
594 .. method:: exec_module(module)
611 when implemented, helps a module to be executed as a script. The ABC
616 An abstract method that is to return the value of :attr:`__file__` for
617 the specified module. If no path is available, :exc:`ImportError` is
620 If source code is available, then the method should return the path to
622 module.
634 The *fullname* argument is a fully resolved name of the module the loader is
635 to handle. The *path* argument is the path to the file for the module.
641 The name of the module the loader can handle.
645 Path to the file of the module.
672 loading is not supported.
679 loading where only bytecode is provided. Bytecode files are an
681 compiler, and so no bytecode-specific API is exposed.
688 - ``'mtime'`` (mandatory): an integer or floating-point number
690 - ``'size'`` (optional): the size in bytes of the source code.
693 extensions. If the path cannot be handled, :exc:`OSError` is raised.
706 This method is deprecated in favour of :meth:`path_stats`. You don't
707 have to implement it, but it is still available for compatibility
719 When writing to the path fails because the path is read-only
730 .. method:: exec_module(module)
749 Concrete implementation of :meth:`InspectLoader.is_package`. A module
750 is determined to be a package if its file path (as provided by
751 :meth:`ExecutionLoader.get_filename`) is a file named
752 ``__init__`` when the file extension is removed **and** the module name
757 :mod:`importlib.machinery` -- Importers and path hooks
758 ------------------------------------------------------
760 .. module:: importlib.machinery
765 --------------
767 This module contains the various objects that help :keyword:`import`
779 A list of strings representing the file suffixes for non-optimized bytecode
805 The value is no longer dependent on ``__debug__``.
817 modules recognized by the standard import machinery. This is a
819 potentially refers to a module without needing any details on the kind
820 of module (for example, :func:`inspect.getmodulename`).
827 An :term:`importer` for built-in modules. All known built-in modules are
879 Class method that attempts to find a :term:`spec <module spec>`
880 for the module specified by *fullname* on :data:`sys.path` or, if
881 defined, on *path*. For each path entry that is searched,
882 :data:`sys.path_importer_cache` is checked. If a non-false object
883 is found then it is used as the :term:`path entry finder` to look
884 for the module being searched for. If no entry is found in
885 :data:`sys.path_importer_cache`, then :data:`sys.path_hooks` is
886 searched for a finder for the path entry and, if found, is stored
888 the module. If no finder is ever found then ``None`` is both
894 If the current working directory -- represented by an empty string --
895 is no longer valid then ``None`` is returned but no value is cached
925 The *path* argument is the directory for which the finder is in charge of
928 The *loader_details* argument is a variable number of 2-item tuples each
931 the module's name and the path to the file found.
934 for each module search to verify the cache is not outdated. Because cache
936 information of the file system, there is a potential race condition of
937 searching for a module, creating a new file, and then searching for the
938 module the new file represents. If the operations happen fast enough to fit
939 within the granularity of stat calls, then the module search will fail. To
940 prevent this from happening, when you create a module dynamically, make sure
969 An instance of :class:`FileFinder` is returned by the closure using the
973 If the argument to the closure is not an existing directory,
974 :exc:`ImportError` is raised.
987 The name of the module that this loader will handle.
1008 specifying the name of the module to load is optional.
1029 The name of the module the loader will handle.
1037 Determines if the module is a package based on :attr:`path`.
1045 Returns ``None`` as bytecode files have no source when this loader is
1051 specifying the name of the module to load is optional.
1063 The *fullname* argument specifies the name of the module the loader is to
1064 support. The *path* argument is the path to the extension module's file.
1070 Name of the module the loader supports.
1074 Path to the extension module.
1078 Creates the module object from the given specification in accordance
1083 .. method:: exec_module(module)
1085 Initializes the given module object in accordance with :pep:`489`.
1092 module based on :attr:`EXTENSION_SUFFIXES`.
1112 namespace packages. This is an alias for a private class and is only made
1129 A specification for a module's import-system-related state. This is
1130 typically exposed as the module's :attr:`__spec__` attribute. In the
1132 attribute available directly on the module object,
1133 e.g. ``module.__spec__.origin == module.__file__``. Note, however, that
1134 while the *values* are usually equivalent, they can differ since there is
1135 no synchronization between the two objects. For example, it is possible to update
1136 the module's :attr:`__file__` at runtime and this will not be automatically
1137 reflected in the module's :attr:`__spec__.origin`, and vice versa.
1145 The module's fully qualified name.
1146 The :term:`finder` should always set this attribute to a non-empty string.
1152 The :term:`loader` used to load the module.
1159 The location the :term:`loader` should use to load the module.
1160 For example, for modules loaded from a .py file this is the filename.
1162 for the :term:`loader` to use. In the uncommon case that there is not one
1170 Most of the time this is a single directory.
1172 to the import system that the module is a package. It should be set to ``None`` for
1173 non-package modules. It is set automatically later to a special object for
1179 module-specific data to use when loading the module. Otherwise it should be
1186 The filename of a compiled version of the module's code.
1194 (Read-only) The fully qualified name of the package the module is in (or the
1195 empty string for a top-level module).
1196 If the module is a package then this is the same as :attr:`name`.
1201 ``False`` otherwise. This value impacts how :attr:`origin` is interpreted
1202 and how the module's :attr:`__file__` is populated.
1205 :mod:`importlib.util` -- Utility code for importers
1206 ---------------------------------------------------
1208 .. module:: importlib.util
1214 --------------
1216 This module contains the various objects that help in the construction of
1228 Return the :pep:`3147`/:pep:`488` path to the byte-compiled file associated
1229 with the source *path*. For example, if *path* is ``/foo/bar/baz.py`` the return
1230 value would be ``/foo/bar/__pycache__/baz.cpython-32.pyc`` for Python 3.2.
1231 The ``cpython-32`` string comes from the current magic tag (see
1232 :func:`get_tag`; if :attr:`sys.implementation.cache_tag` is not defined then
1235 The *optimization* parameter is used to specify the optimization level of the
1238 bytecode path of ``/foo/bar/__pycache__/baz.cpython-32.pyc``. ``None`` causes
1240 representation is used, so ``/foo/bar/baz.py`` with an *optimization* of
1242 ``/foo/bar/__pycache__/baz.cpython-32.opt-2.pyc``. The string representation
1243 of *optimization* can only be alphanumeric, else :exc:`ValueError` is raised.
1245 The *debug_override* parameter is deprecated and can be used to override
1246 the system's value for ``__debug__``. A ``True`` value is the equivalent of
1247 setting *optimization* to the empty string. A ``False`` value is the same as
1249 are not ``None`` then :exc:`TypeError` is raised.
1258 Accepts a :term:`path-like object`.
1264 file path. For example, if *path* is
1265 ``/foo/bar/__pycache__/baz.cpython-32.pyc`` the returned path would be
1267 to :pep:`3147` or :pep:`488` format, a :exc:`ValueError` is raised. If
1268 :attr:`sys.implementation.cache_tag` is not defined,
1269 :exc:`NotImplementedError` is raised.
1274 Accepts a :term:`path-like object`.
1286 Resolve a relative module name to an absolute one.
1288 If **name** has no leading dots, then **name** is simply returned. This
1291 check to see if the **package** argument is needed.
1293 :exc:`ImportError` is raised if **name** is a relative module name but
1294 **package** is a false value (e.g. ``None`` or the empty string).
1295 :exc:`ImportError` is also raised if a relative name would escape its
1308 Find the :term:`spec <module spec>` for a module, optionally relative to
1309 the specified **package** name. If the module is in :attr:`sys.modules`,
1310 then ``sys.modules[name].__spec__`` is returned (unless the spec would be
1311 ``None`` or is not set, in which case :exc:`ValueError` is raised).
1312 Otherwise a search using :attr:`sys.meta_path` is done. ``None`` is
1313 returned if no spec is found.
1315 If **name** is for a submodule (contains a dot), the parent module is
1324 **package** is in fact not a package (i.e. lacks a :attr:`__path__`
1329 Create a new module based on **spec** and
1333 does not return ``None``, then any pre-existing attributes will not be reset.
1335 **spec** or setting an attribute on the module.
1337 This function is preferred over using :class:`types.ModuleType` to create a
1338 new module as **spec** is used to set as many import-controlled attributes on
1339 the module as possible.
1347 module object to load with. The decorated method is expected to have a call
1349 (e.g. ``load_module(self, module)``) for which the second argument
1350 will be the module **object** to be used by the loader.
1354 The decorated method will take in the **name** of the module to be loaded
1355 as expected for a :term:`loader`. If the module is not found in
1356 :data:`sys.modules` then a new one is constructed. Regardless of where the
1357 module came from, :attr:`__loader__` set to **self** and :attr:`__package__`
1358 is set based on what :meth:`importlib.abc.InspectLoader.is_package` returns
1362 If an exception is raised by the decorated method and a module was added to
1363 :data:`sys.modules`, then the module will be removed to prevent a partially
1364 initialized module from being in left in :data:`sys.modules`. If the module
1365 was already in :data:`sys.modules` then it is left alone.
1383 attribute on the returned module. If the attribute is already set the
1384 decorator does nothing. It is assumed that the first positional argument to
1385 the wrapped method (i.e. ``self``) is what :attr:`__loader__` should be set
1398 :attr:`__package__` attribute on the returned module. If :attr:`__package__`
1399 is set and has a value other than ``None`` it will not be changed.
1419 module will be file-based.
1424 Accepts a :term:`path-like object`.
1428 Return the hash of *source_bytes* as bytes. A hash-based ``.pyc`` file embeds
1436 A class which postpones the execution of the loader of a module until the
1437 module has an attribute accessed.
1440 :meth:`~importlib.abc.Loader.exec_module` as control over what module type
1441 is used for the module is required. For those same reasons, the loader's
1445 placed into :attr:`sys.modules` will not work as there is no way to properly
1446 replace the module references throughout the interpreter safely;
1447 :exc:`ValueError` is raised if such a substitution is detected.
1450 For projects where startup time is critical, this class allows for
1451 potentially minimizing the cost of loading a module if it is never used.
1452 For projects where startup time is not essential then use of this class is
1466 is meant to be used in situations where the loader is passed by class
1475 .. _importlib-examples:
1478 --------
1483 To programmatically import a module, use :func:`importlib.import_module`.
1491 Checking if a module can be imported
1494 If you need to find out if a module can be imported without actually doing the
1497 Note that if ``name`` is a submodule (contains a dot),
1498 :func:`importlib.util.find_spec` will import the parent module.
1509 elif (spec := importlib.util.find_spec(name)) is not None:
1511 module = importlib.util.module_from_spec(spec)
1512 sys.modules[name] = module
1513 spec.loader.exec_module(module)
1516 print(f"can't find the {name!r} module")
1533 module = importlib.util.module_from_spec(spec)
1534 sys.modules[module_name] = module
1535 spec.loader.exec_module(module)
1549 ... module = importlib.util.module_from_spec(spec)
1550 ... sys.modules[name] = module
1551 ... loader.exec_module(module)
1552 ... return module
1555 >>> #lazy_typing is a real module object,
1556 >>> #but it is not loaded in memory yet.
1569 former is what you would put on :attr:`sys.meta_path` while the latter is what
1599 Import itself is implemented in Python code, making it possible to
1623 if spec is not None:
1626 msg = f'No module named {absolute_name!r}'
1628 module = importlib.util.module_from_spec(spec)
1629 sys.modules[absolute_name] = module
1630 spec.loader.exec_module(module)
1631 if path is not None:
1632 setattr(parent_module, child_name, module)
1633 return module