Back to module index
Go to module by name
importlib
importlib.abc
Abstract base classes related to import.
Classes
ExecutionLoader
Abstract base class for loaders that wish to support the execution of
modules as scripts.
This ABC represents one of the optional protocols specified in PEP 302.
create_module(self, spec)
Return a module to initialize and into which to load.
This method should raise ImportError if anything prevents it
from creating a new module. It may return None to indicate
that the spec should create the new module.
exec_module(self, module)
Execute the module.
get_code(self, fullname)
Method to return the code object for fullname.
Should return None if not applicable (e.g. built-in module).
Raise ImportError if the module cannot be found.
get_filename(self, fullname)
Abstract method which should return the value that __file__ is to be
set to.
Raises ImportError if the module cannot be found.
get_source(self, fullname)
Abstract method which should return the source code for the
module. The fullname is a str. Returns a str.
Raises ImportError if the module cannot be found.
is_package(self, fullname)
Optional method which when implemented should return whether the
module is a package. The fullname is a str. Returns a bool.
Raises ImportError if the module cannot be found.
load_module(self, fullname)
This module is deprecated.
module_repr(self, module)
Return a module's repr.
Used by the module type when the method does not raise
NotImplementedError.
This method is deprecated.
source_to_code(data, path='<string>')
Compile 'data' into a code object.
The 'data' argument can be anything that compile() can handle. The'path'
argument should be where the data was retrieved (when applicable).
FileLoader
Abstract base class partially implementing the ResourceLoader and
ExecutionLoader ABCs.
contents(self)
create_module(self, spec)
Return a module to initialize and into which to load.
This method should raise ImportError if anything prevents it
from creating a new module. It may return None to indicate
that the spec should create the new module.
exec_module(self, module)
Execute the module.
get_code(self, fullname)
Method to return the code object for fullname.
Should return None if not applicable (e.g. built-in module).
Raise ImportError if the module cannot be found.
get_data(self, path)
Return the data from path as raw bytes.
get_filename(self, name=None, *args, **kwargs)
Return the path to the source file as found by the finder.
get_resource_reader(self, name=None, *args, **kwargs)
get_source(self, fullname)
Abstract method which should return the source code for the
module. The fullname is a str. Returns a str.
Raises ImportError if the module cannot be found.
is_package(self, fullname)
Optional method which when implemented should return whether the
module is a package. The fullname is a str. Returns a bool.
Raises ImportError if the module cannot be found.
is_resource(self, name)
load_module(self, name=None, *args, **kwargs)
Load a module from a file.
This method is deprecated. Use exec_module() instead.
module_repr(self, module)
Return a module's repr.
Used by the module type when the method does not raise
NotImplementedError.
This method is deprecated.
open_resource(self, resource)
resource_path(self, resource)
source_to_code(data, path='<string>')
Compile 'data' into a code object.
The 'data' argument can be anything that compile() can handle. The'path'
argument should be where the data was retrieved (when applicable).
Finder
Legacy abstract base class for import finders.
It may be subclassed for compatibility with legacy third party
reimplementations of the import system. Otherwise, finder
implementations should derive from the more specific MetaPathFinder
or PathEntryFinder ABCs.
Deprecated since Python 3.3
find_module(self, fullname, path=None)
An abstract method that should find a module.
The fullname is a str and the optional path is a str or None.
Returns a Loader object or None.
InspectLoader
Abstract base class for loaders which support inspection about the
modules they can load.
This ABC represents one of the optional protocols specified by PEP 302.
create_module(self, spec)
Return a module to initialize and into which to load.
This method should raise ImportError if anything prevents it
from creating a new module. It may return None to indicate
that the spec should create the new module.
exec_module(self, module)
Execute the module.
get_code(self, fullname)
Method which returns the code object for the module.
The fullname is a str. Returns a types.CodeType if possible, else
returns None if a code object does not make sense
(e.g. built-in module). Raises ImportError if the module cannot be
found.
get_source(self, fullname)
Abstract method which should return the source code for the
module. The fullname is a str. Returns a str.
Raises ImportError if the module cannot be found.
is_package(self, fullname)
Optional method which when implemented should return whether the
module is a package. The fullname is a str. Returns a bool.
Raises ImportError if the module cannot be found.
load_module(self, fullname)
This module is deprecated.
module_repr(self, module)
Return a module's repr.
Used by the module type when the method does not raise
NotImplementedError.
This method is deprecated.
source_to_code(data, path='<string>')
Compile 'data' into a code object.
The 'data' argument can be anything that compile() can handle. The'path'
argument should be where the data was retrieved (when applicable).
Loader
Abstract base class for import loaders.
create_module(self, spec)
Return a module to initialize and into which to load.
This method should raise ImportError if anything prevents it
from creating a new module. It may return None to indicate
that the spec should create the new module.
load_module(self, fullname)
Return the loaded module.
The module must be added to sys.modules and have import-related
attributes set properly. The fullname is a str.
ImportError is raised on failure.
This method is deprecated in favor of loader.exec_module(). If
exec_module() exists then it is used to provide a backwards-compatible
functionality for this method.
module_repr(self, module)
Return a module's repr.
Used by the module type when the method does not raise
NotImplementedError.
This method is deprecated.
MetaPathFinder
Abstract base class for import finders on sys.meta_path.
find_module(self, fullname, path)
Return a loader for the module.
If no module is found, return None. The fullname is a str and
the path is a list of strings or None.
This method is deprecated since Python 3.4 in favor of
finder.find_spec(). If find_spec() exists then backwards-compatible
functionality is provided for this method.
invalidate_caches(self)
An optional method for clearing the finder's cache, if any.
This method is used by importlib.invalidate_caches().
PathEntryFinder
Abstract base class for path entry finders used by PathFinder.
find_loader(self, fullname)
Return (loader, namespace portion) for the path entry.
The fullname is a str. The namespace portion is a sequence of
path entries contributing to part of a namespace package. The
sequence may be empty. If loader is not None, the portion will
be ignored.
The portion will be discarded if another path entry finder
locates the module as a normal module or package.
This method is deprecated since Python 3.4 in favor of
finder.find_spec(). If find_spec() is provided than backwards-compatible
functionality is provided.
_find_module_shim(self, fullname)
Try to find a loader for the specified module by delegating to
self.find_loader().
This method is deprecated in favor of finder.find_spec().
invalidate_caches(self)
An optional method for clearing the finder's cache, if any.
This method is used by PathFinder.invalidate_caches().
Protocol
Base class for protocol classes.
Protocol classes are defined as::
class Proto(Protocol):
def meth(self) -> int:
...
Such classes are primarily used with static type checkers that recognize
structural subtyping (static duck-typing), for example::
class C:
def meth(self) -> int:
return 0
def func(x: Proto) -> int:
return x.meth()
func(C()) # Passes static type check
See PEP 544 for details. Protocol classes decorated with
@typing.runtime_checkable act as simple-minded runtime protocols that check
only the presence of given attributes, ignoring their type signatures.
Protocol classes can be generic, they are defined as::
class GenProto(Protocol[T]):
def meth(self) -> T:
...
ResourceLoader
Abstract base class for loaders which can return data from their
back-end storage.
This ABC represents one of the optional protocols specified by PEP 302.
create_module(self, spec)
Return a module to initialize and into which to load.
This method should raise ImportError if anything prevents it
from creating a new module. It may return None to indicate
that the spec should create the new module.
get_data(self, path)
Abstract method which when implemented should return the bytes for
the specified path. The path must be a str.
load_module(self, fullname)
Return the loaded module.
The module must be added to sys.modules and have import-related
attributes set properly. The fullname is a str.
ImportError is raised on failure.
This method is deprecated in favor of loader.exec_module(). If
exec_module() exists then it is used to provide a backwards-compatible
functionality for this method.
module_repr(self, module)
Return a module's repr.
Used by the module type when the method does not raise
NotImplementedError.
This method is deprecated.
ResourceReader
Abstract base class to provide resource-reading support.
Loaders that support resource reading are expected to implement
the ``get_resource_reader(fullname)`` method and have it either return None
or an object compatible with this ABC.
contents(self)
Return an iterable of strings over the contents of the package.
is_resource(self, name)
Return True if the named 'name' is consider a resource.
open_resource(self, resource)
Return an opened, file-like object for binary reading.
The 'resource' argument is expected to represent only a file name
and thus not contain any subdirectory components.
If the resource cannot be found, FileNotFoundError is raised.
resource_path(self, resource)
Return the file system path to the specified resource.
The 'resource' argument is expected to represent only a file name
and thus not contain any subdirectory components.
If the resource does not exist on the file system, raise
FileNotFoundError.
SourceLoader
Abstract base class for loading source code (and optionally any
corresponding bytecode).
To support loading from source code, the abstractmethods inherited from
ResourceLoader and ExecutionLoader need to be implemented. To also support
loading from bytecode, the optional methods specified directly by this ABC
is required.
Inherited abstractmethods not implemented in this ABC:
* ResourceLoader.get_data
* ExecutionLoader.get_filename
create_module(self, spec)
Use default semantics for module creation.
exec_module(self, module)
Execute the module.
get_code(self, fullname)
Concrete implementation of InspectLoader.get_code.
Reading of bytecode requires path_stats to be implemented. To write
bytecode, set_data must also be implemented.
get_data(self, path)
Abstract method which when implemented should return the bytes for
the specified path. The path must be a str.
get_filename(self, fullname)
Abstract method which should return the value that __file__ is to be
set to.
Raises ImportError if the module cannot be found.
get_source(self, fullname)
Concrete implementation of InspectLoader.get_source.
is_package(self, fullname)
Concrete implementation of InspectLoader.is_package by checking if
the path returned by get_filename has a filename of '__init__.py'.
load_module(self, fullname)
This module is deprecated.
module_repr(self, module)
Return a module's repr.
Used by the module type when the method does not raise
NotImplementedError.
This method is deprecated.
path_mtime(self, path)
Return the (int) modification time for the path (str).
path_stats(self, path)
Return a metadata dict for the source pointed to by the path (str).
Possible keys:
- 'mtime' (mandatory) is the numeric timestamp of last source
code modification;
- 'size' (optional) is the size in bytes of the source code.
set_data(self, path, data)
Write the bytes to the path (if possible).
Accepts a str path and data as bytes.
Any needed intermediary directories are to be created. If for some
reason the file cannot be written because of permissions, fail
silently.
source_to_code(self, data, path, *, _optimize=-1)
Return the code object compiled from source.
The 'data' argument can be any object type that compile() supports.
Traversable
An object with a subset of pathlib.Path methods suitable for
traversing directories and opening files.
is_dir(self)
Return True if self is a dir
is_file(self)
Return True if self is a file
iterdir(self)
Yield Traversable objects in self
joinpath(self, child)
Return Traversable child in self
open(self, mode='r', *args, **kwargs)
mode may be 'r' or 'rb' to open as text or binary. Return a handle
suitable for reading (same as pathlib.Path.open).
When opening as text, accepts encoding parameters such as those
accepted by io.TextIOWrapper.
read_bytes(self)
Read contents of self as bytes
read_text(self, encoding=None)
Read contents of self as bytes
name = <abc.abstractproperty object at 0x7f056745be80>
The base name of this object without any parent references.
TraversableResources
contents(self)
files(self)
Return a Traversable object for the loaded package.
is_resource(self, path)
open_resource(self, resource)
resource_path(self, resource)
Functions
runtime_checkable
runtime_checkable(cls)
Mark a protocol class as a runtime protocol.
Such protocol can be used with isinstance() and issubclass().
Raise TypeError if applied to a non-protocol class.
This allows a simple-minded structural check very similar to
one trick ponies in collections.abc such as Iterable.
For example::
@runtime_checkable
class Closable(Protocol):
def close(self): ...
assert isinstance(open('/some/file'), Closable)
Warning: this will check only the presence of the required methods,
not their type signatures!
Modules
abc
machinery
warnings