💾 Archived View for tris.fyi › pydoc › importlib.resources captured on 2023-04-26 at 13:36:36. Gemini links have been rewritten to link to archived content

View Raw

More Information

⬅️ Previous capture (2023-01-29)

-=-=-=-=-=-=-

Back to module index

Go to module by name

importlib

importlib.resources

This module has no docstring.

Classes

BinaryIO

Typed version of the return of open() in binary mode.
close(self) -> None
fileno(self) -> int
flush(self) -> None
isatty(self) -> bool
read(self, n: int = -1) -> ~AnyStr
readable(self) -> bool
readline(self, limit: int = -1) -> ~AnyStr
readlines(self, hint: int = -1) -> List[~AnyStr]
seek(self, offset: int, whence: int = 0) -> int
seekable(self) -> bool
tell(self) -> int
truncate(self, size: int = None) -> int
writable(self) -> bool
write(self, s: Union[bytes, bytearray]) -> int
writelines(self, lines: List[~AnyStr]) -> None
closed = <property object at 0x7f75e3168540>
mode = <property object at 0x7f75e31684a0>
name = <property object at 0x7f75e31684f0>

BytesIO

Buffered I/O implementation using an in-memory bytes buffer.
close(self, /)

  Disable all I/O operations.
detach(self, /)

  Disconnect this buffer from its underlying raw stream and return it.

  After the raw stream has been detached, the buffer is in an unusable
  state.
fileno(self, /)

  Returns underlying file descriptor if one exists.

  OSError is raised if the IO object does not use a file descriptor.
flush(self, /)

  Does nothing.
getbuffer(self, /)

  Get a read-write view over the contents of the BytesIO object.
getvalue(self, /)

  Retrieve the entire contents of the BytesIO object.
isatty(self, /)

  Always returns False.

  BytesIO objects are not connected to a TTY-like device.
read(self, size=-1, /)

  Read at most size bytes, returned as a bytes object.

  If the size argument is negative, read until EOF is reached.
  Return an empty bytes object at EOF.
read1(self, size=-1, /)

  Read at most size bytes, returned as a bytes object.

  If the size argument is negative or omitted, read until EOF is reached.
  Return an empty bytes object at EOF.
readable(self, /)

  Returns True if the IO object can be read.
readinto(self, buffer, /)

  Read bytes into buffer.

  Returns number of bytes read (0 for EOF), or None if the object
  is set not to block and has no data to read.
readinto1(self, buffer, /)
readline(self, size=-1, /)

  Next line from the file, as a bytes object.

  Retain newline.  A non-negative size argument limits the maximum
  number of bytes to return (an incomplete line may be returned then).
  Return an empty bytes object at EOF.
readlines(self, size=None, /)

  List of bytes objects, each a line from the file.

  Call readline() repeatedly and return a list of the lines so read.
  The optional size argument, if given, is an approximate bound on the
  total number of bytes in the lines returned.
seek(self, pos, whence=0, /)

  Change stream position.

  Seek to byte offset pos relative to position indicated by whence:
       0  Start of stream (the default).  pos should be >= 0;
       1  Current position - pos may be negative;
       2  End of stream - pos usually negative.
  Returns the new absolute position.
seekable(self, /)

  Returns True if the IO object can be seeked.
tell(self, /)

  Current file position, an integer.
truncate(self, size=None, /)

  Truncate the file to at most size bytes.

  Size defaults to the current file position, as returned by tell().
  The current file position is unchanged.  Returns the new size.
writable(self, /)

  Returns True if the IO object can be written.
write(self, b, /)

  Write bytes to file.

  Return the number of bytes written.
writelines(self, lines, /)

  Write lines to the file.

  Note that newlines are not added.  lines can be any iterable object
  producing bytes-like objects. This is equivalent to calling write() for
  each element.
closed = <attribute 'closed' of '_io.BytesIO' objects>
  True if the file is closed.

ModuleSpec

The specification for a module, used for loading.

    A module's spec is the source for information about the module.  For
    data associated with the module, including source, use the spec's
    loader.

    `name` is the absolute name of the module.  `loader` is the loader
    to use when loading the module.  `parent` is the name of the
    package the module is in.  The parent is derived from the name.

    `is_package` determines if the module is considered a package or
    not.  On modules this is reflected by the `__path__` attribute.

    `origin` is the specific location used by the loader from which to
    load the module, if that information is available.  When filename is
    set, origin will match.

    `has_location` indicates that a spec's "origin" reflects a location.
    When this is True, `__file__` attribute of the module is set.

    `cached` is the location of the cached bytecode file, if any.  It
    corresponds to the `__cached__` attribute.

    `submodule_search_locations` is the sequence of path entries to
    search when importing submodules.  If set, is_package should be
    True--and False otherwise.

    Packages are simply modules that (may) have submodules.  If a spec
    has a non-None value in `submodule_search_locations`, the import
    system will consider modules loaded from the spec as packages.

    Only finders (see importlib.abc.MetaPathFinder and
    importlib.abc.PathEntryFinder) should modify ModuleSpec instances.

    
cached = <property object at 0x7f75e3cb9440>
has_location = <property object at 0x7f75e3cb94e0>
parent = <property object at 0x7f75e3cb9350>
  The name of the module's parent.

module

Create a module object.

The name must be a string; the optional doc argument can have any type.

Path

PurePath subclass that can make system calls.

    Path represents a filesystem path but unlike PurePath, also offers
    methods to do system calls on path objects. Depending on your system,
    instantiating a Path will return either a PosixPath or a WindowsPath
    object. You can also instantiate a PosixPath or WindowsPath directly,
    but cannot instantiate a WindowsPath on a POSIX system or vice versa.
    
absolute(self)

  Return an absolute version of this path.  This function works
          even if the path doesn't point to anything.

          No normalization is done, i.e. all '.' and '..' will be kept along.
          Use resolve() to get the canonical path to a file.
        
as_posix(self)

  Return the string representation of the path with forward (/)
          slashes.
as_uri(self)

  Return the path as a 'file' URI.
chmod(self, mode, *, follow_symlinks=True)


          Change the permissions of the path, like os.chmod().
        
cwd()

  Return a new path pointing to the current working directory
          (as returned by os.getcwd()).
        
exists(self)


          Whether this path exists.
        
expanduser(self)

   Return a new path with expanded ~ and ~user constructs
          (as returned by os.path.expanduser)
        
glob(self, pattern)

  Iterate over this subtree and yield all existing files (of any
          kind, including directories) matching the given relative pattern.
        
group(self)


          Return the group name of the file gid.
        
hardlink_to(self, target)


          Make this path a hard link pointing to the same file as *target*.

          Note the order of arguments (self, target) is the reverse of os.link's.
        
home()

  Return a new path pointing to the user's home directory (as
          returned by os.path.expanduser('~')).
        
is_absolute(self)

  True if the path is absolute (has both a root and, if applicable,
          a drive).
is_block_device(self)


          Whether this path is a block device.
        
is_char_device(self)


          Whether this path is a character device.
        
is_dir(self)


          Whether this path is a directory.
        
is_fifo(self)


          Whether this path is a FIFO.
        
is_file(self)


          Whether this path is a regular file (also True for symlinks pointing
          to regular files).
        
is_mount(self)


          Check if this path is a POSIX mount point
        
is_relative_to(self, *other)

  Return True if the path is relative to another path or False.
        
is_reserved(self)

  Return True if the path contains one of the special names reserved
          by the system, if any.
is_socket(self)


          Whether this path is a socket.
        
is_symlink(self)


          Whether this path is a symbolic link.
        
iterdir(self)

  Iterate over the files in this directory.  Does not yield any
          result for the special paths '.' and '..'.
        
joinpath(self, *args)

  Combine this path with one or several arguments, and return a
          new path representing either a subpath (if all arguments are relative
          paths) or a totally different path (if one of the arguments is
          anchored).
        
lchmod(self, mode)


          Like chmod(), except if the path points to a symlink, the symlink's
          permissions are changed, rather than its target's.
        
link_to(self, target)


          Make the target path a hard link pointing to this path.

          Note this function does not make this path a hard link to *target*,
          despite the implication of the function and argument names. The order
          of arguments (target, link) is the reverse of Path.symlink_to, but
          matches that of os.link.

          Deprecated since Python 3.10 and scheduled for removal in Python 3.12.
          Use `hardlink_to()` instead.
        
lstat(self)


          Like stat(), except if the path points to a symlink, the symlink's
          status information is returned, rather than its target's.
        
match(self, path_pattern)


          Return True if this path matches the given pattern.
        
mkdir(self, mode=511, parents=False, exist_ok=False)


          Create a new directory at this given path.
        
open(self, mode='r', buffering=-1, encoding=None, errors=None, newline=None)


          Open the file pointed by this path and return a file object, as
          the built-in open() function does.
        
owner(self)


          Return the login name of the file owner.
        
read_bytes(self)


          Open the file in bytes mode, read it, and close the file.
        
read_text(self, encoding=None, errors=None)


          Open the file in text mode, read it, and close the file.
        
readlink(self)


          Return the path to which the symbolic link points.
        
relative_to(self, *other)

  Return the relative path to another path identified by the passed
          arguments.  If the operation is not possible (because this is not
          a subpath of the other path), raise ValueError.
        
rename(self, target)


          Rename this path to the target path.

          The target path may be absolute or relative. Relative paths are
          interpreted relative to the current working directory, *not* the
          directory of the Path object.

          Returns the new Path instance pointing to the target path.
        
replace(self, target)


          Rename this path to the target path, overwriting if that path exists.

          The target path may be absolute or relative. Relative paths are
          interpreted relative to the current working directory, *not* the
          directory of the Path object.

          Returns the new Path instance pointing to the target path.
        
resolve(self, strict=False)


          Make the path absolute, resolving all symlinks on the way and also
          normalizing it (for example turning slashes into backslashes under
          Windows).
        
rglob(self, pattern)

  Recursively yield all existing files (of any kind, including
          directories) matching the given relative pattern, anywhere in
          this subtree.
        
rmdir(self)


          Remove this directory.  The directory must be empty.
        
samefile(self, other_path)

  Return whether other_path is the same or not as this file
          (as returned by os.path.samefile()).
        
stat(self, *, follow_symlinks=True)


          Return the result of the stat() system call on this path, like
          os.stat() does.
        
symlink_to(self, target, target_is_directory=False)


          Make this path a symlink pointing to the target path.
          Note the order of arguments (link, target) is the reverse of os.symlink.
        
touch(self, mode=438, exist_ok=True)


          Create this file with the given access mode, if it doesn't exist.
        
unlink(self, missing_ok=False)


          Remove this file or link.
          If the path is a directory, use rmdir() instead.
        
with_name(self, name)

  Return a new path with the file name changed.
with_stem(self, stem)

  Return a new path with the stem changed.
with_suffix(self, suffix)

  Return a new path with the file suffix changed.  If the path
          has no suffix, add given suffix.  If the given suffix is an empty
          string, remove the suffix from the path.
        
write_bytes(self, data)


          Open the file in bytes mode, write to it, and close the file.
        
write_text(self, data, encoding=None, errors=None, newline=None)


          Open the file in text mode, write to it, and close the file.
        
anchor = <property object at 0x7f75e2d070b0>
  The concatenation of the drive and root, or ''.
drive = <property object at 0x7f75e2d07010>
  The drive prefix (letter or UNC path), if any.
name = <property object at 0x7f75e2d07100>
  The final path component, if any.
parent = <property object at 0x7f75e2d07290>
  The logical parent of the path.
parents = <property object at 0x7f75e2d072e0>
  A sequence of this path's logical parents.
parts = <property object at 0x7f75e2d07240>
  An object providing sequence-like access to the
          components in the filesystem path.
root = <property object at 0x7f75e2d07060>
  The root of the path, if any.
stem = <property object at 0x7f75e2d071f0>
  The final path component, minus its last suffix.
suffix = <property object at 0x7f75e2d07150>

          The final component's last suffix, if any.

          This includes the leading period. For example: '.txt'
        
suffixes = <property object at 0x7f75e2d071a0>

          A list of the final component's suffixes, if any.

          These include the leading periods. For example: ['.tar', '.gz']
        

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 for loaders to provide resource reading support.
contents(self) -> Iterable[str]

  Return an iterable of entries in `package`.
is_resource(self, path: str) -> bool

  Return True if the named 'path' is a resource.

          Files are resources, directories are not.
        
open_resource(self, resource: str) -> <class 'BinaryIO'>

  Return an opened, file-like object for binary reading.

          The 'resource' argument is expected to represent only a file name.
          If the resource cannot be found, FileNotFoundError is raised.
        
resource_path(self, resource: str) -> str

  Return the file system path to the specified resource.

          The 'resource' argument is expected to represent only a file name.
          If the resource does not exist on the file system, raise
          FileNotFoundError.
        

Sequence

All the operations on a read-only sequence.

    Concrete subclasses must override __new__ or __init__,
    __getitem__, and __len__.
    
count(self, value)

  S.count(value) -> integer -- return number of occurrences of value
index(self, value, start=0, stop=None)

  S.index(value, [start, [stop]]) -> integer -- return first index of value.
             Raises ValueError if the value is not present.

             Supporting start and stop arguments is optional, but
             recommended.
        

TextIO

Typed version of the return of open() in text mode.
close(self) -> None
fileno(self) -> int
flush(self) -> None
isatty(self) -> bool
read(self, n: int = -1) -> ~AnyStr
readable(self) -> bool
readline(self, limit: int = -1) -> ~AnyStr
readlines(self, hint: int = -1) -> List[~AnyStr]
seek(self, offset: int, whence: int = 0) -> int
seekable(self) -> bool
tell(self) -> int
truncate(self, size: int = None) -> int
writable(self) -> bool
write(self, s: ~AnyStr) -> int
writelines(self, lines: List[~AnyStr]) -> None
buffer = <property object at 0x7f75e31689a0>
closed = <property object at 0x7f75e3168540>
encoding = <property object at 0x7f75e31689f0>
errors = <property object at 0x7f75e3168b30>
line_buffering = <property object at 0x7f75e3168b80>
mode = <property object at 0x7f75e31684a0>
name = <property object at 0x7f75e31684f0>
newlines = <property object at 0x7f75e3168bd0>

TextIOWrapper

Character and line based layer over a BufferedIOBase object, buffer.

encoding gives the name of the encoding that the stream will be
decoded or encoded with. It defaults to locale.getpreferredencoding(False).

errors determines the strictness of encoding and decoding (see
help(codecs.Codec) or the documentation for codecs.register) and
defaults to "strict".

newline controls how line endings are handled. It can be None, '',
'\n', '\r', and '\r\n'.  It works as follows:


  enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
  these are translated into '\n' before being returned to the
  caller. If it is '', universal newline mode is enabled, but line
  endings are returned to the caller untranslated. If it has any of
  the other legal values, input lines are only terminated by the given
  string, and the line ending is returned to the caller untranslated.


  translated to the system default line separator, os.linesep. If
  newline is '' or '\n', no translation takes place. If newline is any
  of the other legal values, any '\n' characters written are translated
  to the given string.

If line_buffering is True, a call to flush is implied when a call to
write contains a newline character.
close(self, /)
detach(self, /)
fileno(self, /)
flush(self, /)
isatty(self, /)
read(self, size=-1, /)
readable(self, /)
readline(self, size=-1, /)
readlines(self, hint=-1, /)

  Return a list of lines from the stream.

  hint can be specified to control the number of lines read: no more
  lines will be read if the total size (in bytes/characters) of all
  lines so far exceeds hint.
reconfigure(self, /, *, encoding=None, errors=None, newline=None, line_buffering=None, write_through=None)

  Reconfigure the text stream with new parameters.

  This also does an implicit stream flush.
seek(self, cookie, whence=0, /)
seekable(self, /)
tell(self, /)
truncate(self, pos=None, /)
writable(self, /)
write(self, text, /)
writelines(self, lines, /)

  Write a list of lines to stream.

  Line separators are not added, so it is usual for each of the
  lines provided to have a line separator at the end.
buffer = <member 'buffer' of '_io.TextIOWrapper' objects>
closed = <attribute 'closed' of '_io.TextIOWrapper' objects>
encoding = <member 'encoding' of '_io.TextIOWrapper' objects>
errors = <attribute 'errors' of '_io.TextIOWrapper' objects>
line_buffering = <member 'line_buffering' of '_io.TextIOWrapper' objects>
name = <attribute 'name' of '_io.TextIOWrapper' objects>
newlines = <attribute 'newlines' of '_io.TextIOWrapper' objects>
write_through = <member 'write_through' of '_io.TextIOWrapper' objects>

suppress

Context manager to suppress specified exceptions

    After the exception is suppressed, execution proceeds with the next
    statement following the with statement.

         with suppress(FileNotFoundError):
             os.remove(somefile)
         # Execution still resumes here if the file was already removed
    

Functions

as_file

as_file(path)


      Given a Traversable object, return that object as a
      path on the local file system in a context manager.
    

cast

cast(typ, val)

  Cast a value to a type.

      This returns the value unchanged.  To the type checker this
      signals that the return value has the designated type, but at
      runtime we intentionally don't check anything (we want this
      to be as fast as possible).
    

contents

contents(package: Union[str, module]) -> Iterable[str]

  Return an iterable of entries in 'package'.

      Note that not all entries are resources.  Specifically, directories are
      not considered resources.  Use `is_resource()` on each entry returned here
      to check if it is a resource or not.
    

files

files(package)


      Get a Traversable resource from a package
    

is_resource

is_resource(package: Union[str, module], name: str) -> bool

  True if 'name' is a resource inside 'package'.

      Directories are *not* resources.
    

open_binary

open_binary(package: Union[str, module], resource: Union[str, os.PathLike]) -> <class 'BinaryIO'>

  Return a file-like object opened for binary reading of the resource.

open_text

open_text(package: Union[str, module], resource: Union[str, os.PathLike], encoding: str = 'utf-8', errors: str = 'strict') -> <class 'TextIO'>

  Return a file-like object opened for text reading of the resource.

path

path(package: Union[str, module], resource: Union[str, os.PathLike]) -> 'ContextManager[Path]'

  A context manager providing a file path object to the resource.

      If the resource does not already exist on its own on the file system,
      a temporary file will be created. If the file was created, the file
      will be deleted upon exiting the context manager (no exception is
      raised if the file was deleted prior to the context manager
      exiting).
    

read_binary

read_binary(package: Union[str, module], resource: Union[str, os.PathLike]) -> bytes

  Return the binary contents of the resource.

read_text

read_text(package: Union[str, module], resource: Union[str, os.PathLike], encoding: str = 'utf-8', errors: str = 'strict') -> str

  Return the decoded string of the resource.

      The decoding-related arguments have the same semantics as those of
      bytes.decode().
    

singledispatch

singledispatch(func)

  Single-dispatch generic function decorator.

      Transforms a function into a generic function, which can have different
      behaviours depending upon the type of its first argument. The decorated
      function acts as the default implementation, and additional
      implementations can be registered using the register() attribute of the
      generic function.
    

Other members

ContextManager = typing.ContextManager
  A generic version of contextlib.AbstractContextManager.
Iterable = typing.Iterable
  A generic version of collections.abc.Iterable.
Package = typing.Union[str, module]
Resource = typing.Union[str, os.PathLike]
Union = typing.Union
  Union type; Union[X, Y] means either X or Y.

      To define a union, use e.g. Union[int, str].  Details:
      - The arguments must be types and there must be at least one.
      - None as an argument is a special case and is replaced by
        type(None).
      - Unions of unions are flattened, e.g.::

          Union[Union[int, str], float] == Union[int, str, float]

      - Unions of a single argument vanish, e.g.::

          Union[int] == int  # The constructor actually returns int

      - Redundant arguments are skipped, e.g.::

          Union[int, str, int] == Union[int, str]

      - When comparing unions, the argument order is ignored, e.g.::

          Union[int, str] == Union[str, int]

      - You cannot subclass or instantiate a union.
      - You can use Optional[X] as a shorthand for Union[X, None].
    

Modules

io

os