New in version 3.1.
The purpose of theimportlib package is two-fold. One is to provide theimplementation of theimport statement (and thus, by extension, the__import__() function) in Python source code. This provides animplementation ofimport which is portable to any Pythoninterpreter. This also provides an implementation which is easier tocomprehend than one implemented in a programming language other than Python.
Two, the components to implementimport are exposed in thispackage, making it easier for users to create their own custom objects (knowngenerically as animporter) to participate in the import process.
See also
An implementation of the built-in__import__() function.
Import a module. Thename argument specifies what module toimport in absolute or relative terms(e.g. eitherpkg.mod or..mod). If the name isspecified in relative terms, then thepackage argument must be set tothe name of the package which is to act as the anchor for resolving thepackage name (e.g.import_module('..mod','pkg.subpkg') will importpkg.mod).
Theimport_module() function acts as a simplifying wrapper aroundimportlib.__import__(). This means all semantics of the function arederived fromimportlib.__import__(), including requiring the packagefrom which an import is occurring to have been previously imported(i.e.,package must already be imported). The most important differenceis thatimport_module() returns the specified package or module(e.g.pkg.mod), while__import__() returns thetop-level package or module (e.g.pkg).
Changed in version 3.3:Parent packages are automatically imported.
Find the loader for a module, optionally within the specifiedpath. If themodule is insys.modules, thensys.modules[name].__loader__ isreturned (unless the loader would beNone, in which caseValueError is raised). Otherwise a search usingsys.meta_pathis done.None is returned if no loader is found.
A dotted name does not have its parent’s implicitly imported as that requiresloading them and that may not be desired. To properly import a submodule youwill need to import all parent packages of the submodule and use the correctargument topath.
Invalidate the internal caches of finders stored atsys.meta_path. If a finder implementsinvalidate_caches() then itwill be called to perform the invalidation. This function should be calledif any modules are created/installed while your program is running toguarantee all finders will notice the new module’s existence.
New in version 3.3.
Theimportlib.abc module contains all of the core abstract base classesused byimport. Some subclasses of the core abstract base classesare also provided to help in implementing the core ABCs.
ABC hierarchy:
object+--Finder(deprecated)|+--MetaPathFinder|+--PathEntryFinder+--Loader+--ResourceLoader--------++--InspectLoader|+--ExecutionLoader--++--FileLoader+--SourceLoader+--PyLoader(deprecated)+--PyPycLoader(deprecated)
An abstract base class representing afinder.
Deprecated since version 3.3:UseMetaPathFinder orPathEntryFinder instead.
An abstact method for finding aloader for the specifiedmodule. Originally specified inPEP 302, this method was meantfor use insys.meta_path and in the path-based import subsystem.
An abstract base class representing ameta path finder. Forcompatibility, this is a subclass ofFinder.
New in version 3.3.
An abstract method for finding aloader for the specifiedmodule. If this is a top-level import,path will beNone.Otherwise, this is a search for a subpackage or module andpathwill be the value of__path__ from the parentpackage. If a loader cannot be found,None is returned.
An optional method which, when called, should invalidate any internalcache used by the finder. Used byimportlib.invalidate_caches()when invalidating the caches of all finders onsys.meta_path.
An abstract base class representing apath entry finder. Thoughit bears some similarities toMetaPathFinder,PathEntryFinderis meant for use only within the path-based import subsystem providedbyPathFinder. This ABC is a subclass ofFinder forcompatibility.
New in version 3.3.
An abstract method for finding aloader for the specifiedmodule. Returns a 2-tuple of(loader,portion) whereportionis a sequence of file system locations contributing to part of a namespacepackage. The loader may beNone while specifyingportion tosignify the contribution of the file system locations to a namespacepackage. An empty list can be used forportion to signify the loaderis not part of a package. Ifloader isNone andportion isthe empty list then no loader or location for a namespace package werefound (i.e. failure to find anything for the module).
A concrete implementation ofFinder.find_module() which isequivalent toself.find_loader(fullname)[0].
An optional method which, when called, should invalidate any internalcache used by the finder. Used byPathFinder.invalidate_caches()when invalidating the caches of all cached finders.
An abstract base class for aloader.SeePEP 302 for the exact definition for a loader.
An abstract method for loading a module. If the module cannot beloaded,ImportError is raised, otherwise the loaded module isreturned.
If the requested module already exists insys.modules, thatmodule should be used and reloaded.Otherwise the loader should create a new module and insert it intosys.modules before any loading begins, to prevent recursionfrom the import. If the loader inserted a module and the load fails, itmust be removed by the loader fromsys.modules; modules alreadyinsys.modules before the loader began execution should be leftalone. Theimportlib.util.module_for_loader() decorator handlesall of these details.
The loader should set several attributes on the module.(Note that some of these attributes can change when a module isreloaded.)
The name of the module.
The path to where the module data is stored (not set for built-inmodules).
The path to where a compiled version of the module is/should bestored (not set when the attribute would be inappropriate).
A list of strings specifying the search path within apackage. This attribute is not set on modules.
The parent package for the module/package. If the module istop-level then it has a value of the empty string. Theimportlib.util.set_package() decorator can handle the detailsfor__package__.
The loader used to load the module.(This is not set by the built-in import machinery,but it should be set whenever aloader is used.)
An abstract method which when implemented calculates and returns thegiven module’s repr, as a string.
An abstract base class for aloader which implements the optionalPEP 302 protocol for loading arbitrary resources from the storageback-end.
An abstract method to return the bytes for the data located atpath.Loaders that have a file-like storage back-endthat allows storing arbitrary datacan implement this abstract method to give direct accessto the data stored.IOError is to be raised if thepath cannotbe found. Thepath is expected to be constructed using a module’s__file__ attribute or an item from a package’s__path__.
An abstract base class for aloader which implements the optionalPEP 302 protocol for loaders that inspect modules.
An abstract method to return thecode object for a module.None is returned if the module does not have a code object(e.g. built-in module).ImportError is raised if loader cannotfind the requested module.
An abstract method to return the source of a module. It is returned asa text string usinguniversal newlines, translating allrecognized line separators into'\n' characters. ReturnsNoneif no source is available (e.g. a built-in module). RaisesImportError if the loader cannot find the module specified.
An abstract method to return a true value if the module is a package, afalse value otherwise.ImportError is raised if theloader cannot find the module.
An abstract base class which inherits fromInspectLoader that,when implemented, helps a module to be executed as a script. The ABCrepresents an optionalPEP 302 protocol.
An abstract method that is to return the value of__file__ forthe specified module. If no path is available,ImportError israised.
If source code is available, then the method should return the path tothe source file, regardless of whether a bytecode was used to load themodule.
An abstract base class which inherits fromResourceLoader andExecutionLoader, providing concrete implementations ofResourceLoader.get_data() andExecutionLoader.get_filename().
Thefullname argument is a fully resolved name of the module the loader isto handle. Thepath argument is the path to the file for the module.
New in version 3.3.
The name of the module the loader can handle.
Path to the file of the module.
Calls super’sload_module().
Returns the open, binary file forpath.
An abstract base class for implementing source (and optionally bytecode)file loading. The class inherits from bothResourceLoader andExecutionLoader, requiring the implementation of:
Should only return the path to the source file; sourcelessloading is not supported.
The abstract methods defined by this class are to add optional bytecodefile support. Not implementing these optional methods causes the loader toonly work with source code. Implementing the methods allows the loader towork with sourceand bytecode files; it does not allow forsourcelessloading where only bytecode is provided. Bytecode files are anoptimization to speed up loading by removing the parsing step of Python’scompiler, and so no bytecode-specific API is exposed.
Optional abstract method which returns adict containingmetadata about the specifed path. Supported dictionary keys are:
Any other keys in the dictionary are ignored, to allow for futureextensions.
New in version 3.3.
Optional abstract method which returns the modification time for thespecified path.
Deprecated since version 3.3:This method is deprecated in favour ofpath_stats(). You don’thave to implement it, but it is still available for compatibilitypurposes.
Optional abstract method which writes the specified bytes to a filepath. Any intermediate directories which do not exist are to be createdautomatically.
When writing to the path fails because the path is read-only(errno.EACCES/PermissionError), do not propagate theexception.
Concrete implementation ofInspectLoader.get_code().
Concrete implementation ofLoader.load_module().
Concrete implementation ofInspectLoader.get_source().
Concrete implementation ofInspectLoader.is_package(). A moduleis determined to be a package if its file path (as provided byExecutionLoader.get_filename()) is a file named__init__ when the file extension is removedand the module nameitself does not end in__init__.
An abstract base class inheriting fromExecutionLoader andResourceLoader designed to ease the loading ofPython source modules (bytecode is not handled; seeSourceLoader for a source/bytecode ABC). A subclassimplementing this ABC will only need to worry about exposing how the sourcecode is stored; all other details for loading Python source code will behandled by the concrete implementations of key methods.
Deprecated since version 3.2:This class has been deprecated in favor ofSourceLoader and isslated for removal in Python 3.4. See below for how to create asubclass that is compatible with Python 3.1 onwards.
If compatibility with Python 3.1 is required, then use the following idiomto implement a subclass that will work with Python 3.1 onwards (make sureto implementExecutionLoader.get_filename()):
try:fromimportlib.abcimportSourceLoaderexceptImportError:fromimportlib.abcimportPyLoaderasSourceLoaderclassCustomLoader(SourceLoader):defget_filename(self,fullname):"""Return the path to the source file."""# Implement ...defsource_path(self,fullname):"""Implement source_path in terms of get_filename."""try:returnself.get_filename(fullname)exceptImportError:returnNonedefis_package(self,fullname):"""Implement is_package by looking for an __init__ file name as returned by get_filename."""filename=os.path.basename(self.get_filename(fullname))returnos.path.splitext(filename)[0]=='__init__'
An abstract method that returns the path to the source code for amodule. Should returnNone if there is no source code.RaisesImportError if the loader knows it cannot handle themodule.
A concrete implementation ofimportlib.abc.ExecutionLoader.get_filename() thatrelies onsource_path(). Ifsource_path() returnsNone, thenImportError is raised.
A concrete implementation ofimportlib.abc.Loader.load_module()that loads Python source code. All needed information comes from theabstract methods required by this ABC. The only pertinent assumptionmade by this method is that when loading a package__path__ is set to[os.path.dirname(__file__)].
A concrete implementation ofimportlib.abc.InspectLoader.get_code() that creates code objectsfrom Python source code, by requesting the source code (usingsource_path() andget_data()) and compiling it with thebuilt-incompile() function.
A concrete implementation ofimportlib.abc.InspectLoader.get_source(). Usesimportlib.abc.ResourceLoader.get_data() andsource_path()to get the source code. It tries to guess the source encoding usingtokenize.detect_encoding().
An abstract base class inheriting fromPyLoader.This ABC is meant to help in creating loaders that support both Pythonsource and bytecode.
Deprecated since version 3.2:This class has been deprecated in favor ofSourceLoader and toproperly supportPEP 3147. If compatibility is required withPython 3.1, implement bothSourceLoader andPyLoader;instructions on how to do so are included in the documentation forPyLoader. Do note that this solution will not supportsourceless/bytecode-only loading; only sourceand bytecode loading.
Changed in version 3.3:Updated to parse (but not use) the new source size field in bytecodefiles when reading and to write out the field properly when writing.
An abstract method which returns the modification time for the sourcecode of the specified module. The modification time should be aninteger. If there is no source code, returnNone. If themodule cannot be found thenImportError is raised.
An abstract method which returns the path to the bytecode for thespecified module, if it exists. It returnsNoneif no bytecode exists (yet).RaisesImportError if the loader knows it cannot handle themodule.
A concrete implementation ofExecutionLoader.get_filename() that relies onPyLoader.source_path() andbytecode_path().Ifsource_path() returns a path, then that value is returned.Else ifbytecode_path() returns a path, that path will bereturned. If a path is not available from both methods,ImportError is raised.
An abstract method which has the loader writebytecode for futureuse. If the bytecode is written, returnTrue. ReturnFalse if the bytecode could not be written. This methodshould not be called ifsys.dont_write_bytecode is true.Thebytecode argument should be a bytes string or bytes array.
This module contains the various objects that helpimportfind and load modules.
A list of strings representing the recognized file suffixes for sourcemodules.
New in version 3.3.
A list of strings representing the file suffixes for non-optimized bytecodemodules.
New in version 3.3.
A list of strings representing the file suffixes for optimized bytecodemodules.
New in version 3.3.
A list of strings representing the recognized file suffixes for bytecodemodules. Set to eitherDEBUG_BYTECODE_SUFFIXES orOPTIMIZED_BYTECODE_SUFFIXES based on whether__debug__ is true.
New in version 3.3.
A list of strings representing the recognized file suffixes forextension modules.
New in version 3.3.
Returns a combined list of strings representing all file suffixes formodules recognized by the standard import machinery. This is ahelper for code which simply needs to know if a filesystem pathpotentially refers to a module without needing any details on the kindof module (for example,inspect.getmodulename())
New in version 3.3.
Animporter for built-in modules. All known built-in modules arelisted insys.builtin_module_names. This class implements theimportlib.abc.MetaPathFinder andimportlib.abc.InspectLoader ABCs.
Only class methods are defined by this class to alleviate the need forinstantiation.
Animporter for frozen modules. This class implements theimportlib.abc.MetaPathFinder andimportlib.abc.InspectLoader ABCs.
Only class methods are defined by this class to alleviate the need forinstantiation.
Finder for modules declared in the Windows registry. This classimplements theimportlib.abc.Finder ABC.
Only class methods are defined by this class to alleviate the need forinstantiation.
New in version 3.3.
AFinder forsys.path and package__path__ attributes.This class implements theimportlib.abc.MetaPathFinder ABC.
Only class methods are defined by this class to alleviate the need forinstantiation.
Class method that attempts to find aloader for the modulespecified byfullname onsys.path or, if defined, onpath. For each path entry that is searched,sys.path_importer_cache is checked. If a non-false object isfound then it is used as thepath entry finder to look for themodule being searched for. If no entry is found insys.path_importer_cache, thensys.path_hooks issearched for a finder for the path entry and, if found, is stored insys.path_importer_cache along with being queried about themodule. If no finder is ever found thenNone is both stored inthe cache and returned.
Callsimportlib.abc.PathEntryFinder.invalidate_caches() on allfinders stored insys.path_importer_cache.
A concrete implementation ofimportlib.abc.PathEntryFinder whichcaches results from the file system.
Thepath argument is the directory for which the finder is in charge ofsearching.
Theloader_details argument is a variable number of 2-item tuples eachcontaining a loader and a sequence of file suffixes the loader recognizes.The loaders are expected to be callables which accept two arguments ofthe module’s name and the path to the file found.
The finder will cache the directory contents as necessary, making stat callsfor each module search to verify the cache is not outdated. Because cachestaleness relies upon the granularity of the operating system’s stateinformation of the file system, there is a potential race condition ofsearching for a module, creating a new file, and then searching for themodule the new file represents. If the operations happen fast enough to fitwithin the granularity of stat calls, then the module search will fail. Toprevent this from happening, when you create a module dynamically, make sureto callimportlib.invalidate_caches().
New in version 3.3.
The path the finder will search in.
Clear out the internal cache.
A class method which returns a closure for use onsys.path_hooks.An instance ofFileFinder is returned by the closure using thepath argument given to the closure directly andloader_detailsindirectly.
If the argument to the closure is not an existing directory,ImportError is raised.
A concrete implementation ofimportlib.abc.SourceLoader bysubclassingimportlib.abc.FileLoader and providing some concreteimplementations of other methods.
New in version 3.3.
The name of the module that this loader will handle.
The path to the source file.
Concrete implementation ofimportlib.abc.SourceLoader.path_stats().
Concrete implementation ofimportlib.abc.SourceLoader.set_data().
A concrete implementation ofimportlib.abc.FileLoader which canimport bytecode files (i.e. no source code files exist).
Please note that direct use of bytecode files (and thus not source codefiles) inhibits your modules from being usable by all Pythonimplementations or new versions of Python which change the bytecodeformat.
New in version 3.3.
The name of the module the loader will handle.
The path to the bytecode file.
ReturnsNone as bytecode files have no source when this loader isused.
A concrete implementation ofimportlib.abc.InspectLoader forextension modules.
Thefullname argument specifies the name of the module the loader is tosupport. Thepath argument is the path to the extension module’s file.
New in version 3.3.
Name of the module the loader supports.
Path to the extension module.
Loads the extension module if and only iffullname is the same asname or isNone.
ReturnsTrue if the file path points to a package’s__init__module based onEXTENSION_SUFFIXES.
ReturnsNone as extension modules lack a code object.
ReturnsNone as extension modules do not have source code.
This module contains the various objects that help in the construction ofanimporter.
Resolve a relative module name to an absolute one.
Ifname has no leading dots, thenname is simply returned. Thisallows for usage such asimportlib.util.resolve_name('sys',__package__) without doing acheck to see if thepackage argument is needed.
ValueError is raised ifname is a relative module name butpackage is a false value (e.g.None or the empty string).ValueError is also raised a relative name would escape its containingpackage (e.g. requesting..bacon from within thespam package).
New in version 3.3.
Adecorator for aloader method,to handle selecting the propermodule object to load with. The decorated method is expected to have a callsignature taking two positional arguments(e.g.load_module(self,module)) for which the second argumentwill be the moduleobject to be used by the loader.Note that the decorator will not work on static methods because of theassumption of two arguments.
The decorated method will take in thename of the module to be loadedas expected for aloader. If the module is not found insys.modules then a new one is constructed with its__name__ attribute set toname,__loader__ set toself, and__package__ set ifimportlib.abc.InspectLoader.is_package() is defined forself anddoes not raiseImportError forname. If a new module is notneeded then the module found insys.modules will be passed into themethod.
If an exception is raised by the decorated method and a module was added tosys.modules it will be removed to prevent a partially initializedmodule from being in left insys.modules. If the module was alreadyinsys.modules then it is left alone.
Use of this decorator handles all the details of which module object aloader should initialize as specified byPEP 302 as best as possible.
Changed in version 3.3:__loader__ and__package__ are automatically set(when possible).
Note
It is recommended thatmodule_for_loader() be used over thisdecorator as it subsumes this functionality.
Adecorator for aloader to set the__package__attribute on the module returned by the loader. If__package__ isset and has a value other thanNone it will not be changed.Note that the module returned by the loader is what has the attributeset on and not the module found insys.modules.
Reliance on this decorator is discouraged when it is possible to set__package__ before importing. Bysetting it beforehand the code for the module is executed with theattribute set and thus can be used by global level code duringinitialization.
Note
It is recommended thatmodule_for_loader() be used over thisdecorator as it subsumes this functionality.
30.5.runpy — Locating and executing Python modules
Enter search terms or a module, class or function name.