• Home
  • Raw
  • Download

Lines Matching +full:import +full:- +full:module

1 :mod:`!importlib` --- The implementation of :keyword:`!import`
4 .. module:: importlib
5 :synopsis: The implementation of the import machinery.
14 --------------
18 ------------
20 The purpose of the :mod:`importlib` package is three-fold.
23 implementation of the :keyword:`import` statement (and thus, by extension, the
25 implementation of :keyword:`!import` which is portable to any Python
29 Two, the components to implement :keyword:`import` are exposed in this
31 generically as an :term:`importer`) to participate in the import process.
36 * :mod:`importlib.metadata` presents access to metadata from third-party
38 * :mod:`importlib.resources` provides routines for accessing non-code
43 :ref:`import`
44 The language reference for the :keyword:`import` statement.
52 The :keyword:`import` statement is syntactic sugar for this function.
54 :ref:`sys-path-init`
58 Import on Case-Insensitive Platforms
64 New Import Hooks
67 Imports: Multi-Line and Absolute/Relative
70 Main module explicit relative imports
76 A ModuleSpec Type for the Import System
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
108 import in absolute or relative terms
112 package name (e.g. ``import_module('..mod', 'pkg.subpkg')`` will import
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
125 noticed by the import system.
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
139 loading them and that may not be desired. To properly import a submodule you
140 will need to import all parent packages of the submodule and use the correct
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,
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
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
195 When a module is reloaded, its dictionary (containing the module's global
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
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 ---
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
236 :synopsis: Abstract base classes related to import
240 --------------
243 The :mod:`importlib.abc` module contains all of the core abstract base classes
244 used by :keyword:`import`. Some subclasses 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
297 module and *path* will be the value of :attr:`__path__` from the
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*
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
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``
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
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.
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
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.
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__`
468 The import system passes this attribute to ``__import__()`` and to finders
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
490 The recommended API for loading a module is :meth:`exec_module`
492 :meth:`load_module`. The import machinery takes care of all the
496 .. method:: module_repr(module)
499 module's representation, as a string. The module type's default
508 The import machinery now takes care of this automatically.
515 back-end.
524 Loaders that have a file-like storage back-end
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.
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
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
617 the specified module. If no path is available, :exc:`ImportError` is
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.
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.
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
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
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
882 :data:`sys.path_importer_cache` is checked. If a non-false object
884 for the module being searched for. If no entry is found in
888 the module. If no finder is ever found then ``None`` is both
894 If the current working directory -- represented by an empty string --
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
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
987 The name of the module that this loader will handle.
1008 specifying the name of the module to load is optional.
1018 import bytecode files (i.e. no source code files exist).
1029 The name of the module the loader will handle.
1037 Determines if the module is a package based on :attr:`path`.
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`.
1116 >>> from importlib.machinery import NamespaceLoader
1117 >>> import my_namespace
1120 >>> import importlib.abc
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
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.
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`.
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
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
1238 bytecode path of ``/foo/bar/__pycache__/baz.cpython-32.pyc``. ``None`` causes
1242 ``/foo/bar/__pycache__/baz.cpython-32.opt-2.pyc``. The string representation
1258 Accepts a :term:`path-like object`.
1265 ``/foo/bar/__pycache__/baz.cpython-32.pyc`` the returned path would be
1274 Accepts a :term:`path-like object`.
1286 Resolve a relative module name to an absolute one.
1293 :exc:`ImportError` is raised if **name** is a relative module name but
1302 To improve consistency with import statements, raise
1304 import attempts.
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`,
1315 If **name** is for a submodule (contains a dot), the parent module is
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.
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
1357 module came from, :attr:`__loader__` set to **self** and :attr:`__package__`
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
1376 The import machinery now directly performs all the functionality
1383 attribute on the returned module. If the attribute is already set the
1393 The import machinery takes care of this automatically.
1398 :attr:`__package__` attribute on the returned module. If :attr:`__package__`
1402 The import machinery takes care of this automatically.
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
1446 replace the module references throughout the interpreter safely;
1451 potentially minimizing the cost of loading a module if it is never used.
1475 .. _importlib-examples:
1478 --------
1483 To programmatically import a module, use :func:`importlib.import_module`.
1486 import importlib
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
1495 import, then you should use :func:`importlib.util.find_spec`.
1498 :func:`importlib.util.find_spec` will import the parent module.
1501 import importlib.util
1502 import sys
1510 # If you chose to perform the actual import ...
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")
1522 To import a Python source file directly, use the following recipe::
1524 import importlib.util
1525 import sys
1528 import tokenize
1533 module = importlib.util.module_from_spec(spec)
1534 sys.modules[module_name] = module
1535 spec.loader.exec_module(module)
1543 >>> import importlib.util
1544 >>> import sys
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,
1565 For deep customizations of import, you typically want to implement an
1572 show you how to register your own importers so that import will use them (for
1576 import importlib.machinery
1577 import sys
1599 Import itself is implemented in Python code, making it possible to
1600 expose most of the import machinery through importlib. The following
1605 import importlib.util
1606 import sys
1609 """An approximate implementation of import."""
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)
1632 setattr(parent_module, child_name, module)
1633 return module