Back to module index

Go to module by name

importlib

importlib.metadata (package)

This module has no docstring.

Classes

Deprecated


    Compatibility add-in for mapping to indicate that
    mapping behavior is deprecated.

    >>> recwarn = getfixture('recwarn')
    >>> class DeprecatedDict(Deprecated, dict): pass
    >>> dd = DeprecatedDict(foo='bar')
    >>> dd.get('baz', None)
    >>> dd['foo']
    'bar'
    >>> list(dd)
    ['foo']
    >>> list(dd.keys())
    ['foo']
    >>> 'foo' in dd
    True
    >>> list(dd.values())
    ['bar']
    >>> len(recwarn)
    1
    
get(self, name, default=None)
keys(self)
values(self)

DeprecatedList


    Allow an otherwise immutable object to implement mutability
    for compatibility.

    >>> recwarn = getfixture('recwarn')
    >>> dl = DeprecatedList(range(3))
    >>> dl[0] = 1
    >>> dl.append(3)
    >>> del dl[3]
    >>> dl.reverse()
    >>> dl.sort()
    >>> dl.extend([4])
    >>> dl.pop(-1)
    4
    >>> dl.remove(1)
    >>> dl += [5]
    >>> dl + [6]
    [1, 2, 5, 6]
    >>> dl + (6,)
    [1, 2, 5, 6]
    >>> dl.insert(0, 0)
    >>> dl
    [0, 1, 2, 5]
    >>> dl == [0, 1, 2, 5]
    True
    >>> dl == (0, 1, 2, 5)
    True
    >>> len(recwarn)
    1
    
append(self, *args, **kwargs)
clear(self, /)

  Remove all items from list.
copy(self, /)

  Return a shallow copy of the list.
count(self, value, /)

  Return number of occurrences of value.
extend(self, *args, **kwargs)
index(self, value, start=0, stop=9223372036854775807, /)

  Return first index of value.

  Raises ValueError if the value is not present.
insert(self, *args, **kwargs)
pop(self, *args, **kwargs)
remove(self, *args, **kwargs)
reverse(self, *args, **kwargs)
sort(self, *args, **kwargs)

Distribution

A Python distribution package.
at(path)

  Return a Distribution for the indicated metadata path

          :param path: a string or path-like object
          :return: a concrete Distribution instance for the path
        
discover(**kwargs)

  Return an iterable of Distribution objects for all packages.

          Pass a ``context`` or pass keyword arguments for constructing
          a context.

          :context: A ``DistributionFinder.Context`` object.
          :return: Iterable of Distribution objects for all packages.
        
from_name(name)

  Return the Distribution for the given package name.

          :param name: The name of the distribution package to search for.
          :return: The Distribution instance (or subclass thereof) for the named
              package, if found.
          :raises PackageNotFoundError: When the named package's distribution
              metadata cannot be found.
        
locate_file(self, path)


          Given a path to a file in this distribution, return a path
          to it.
        
read_text(self, filename)

  Attempt to load metadata file given by the name.

          :param filename: The name of the file in the distribution info.
          :return: The text if found, otherwise None.
        
entry_points = <property object at 0x7f75e2b313f0>
files = <property object at 0x7f75e2b31440>
  Files in this distribution.

          :return: List of PackagePath for this distribution or None

          Result is `None` if the metadata file that enumerates files
          (i.e. RECORD for dist-info or SOURCES.txt for egg-info) is
          missing.
          Result may be empty if the metadata exists but is empty.
        
metadata = <property object at 0x7f75e2b312b0>
  Return the parsed metadata for this Distribution.

          The returned object will have keys that name the various bits of
          metadata.  See PEP 566 for details.
        
name = <property object at 0x7f75e2b31300>
  Return the 'Name' metadata for the distribution package.
requires = <property object at 0x7f75e2b31490>
  Generated requirements specified for this Distribution
version = <property object at 0x7f75e2b313a0>
  Return the 'Version' metadata for the distribution package.

DistributionFinder


    A MetaPathFinder capable of discovering installed distributions.
    

invalidate_caches.Context


        Keyword arguments presented by the caller to
        ``distributions()`` or ``Distribution.discover()``
        to narrow the scope of a search for distributions
        in all DistributionFinders.

        Each DistributionFinder may expect any parameters
        and should attempt to honor the canonical
        parameters defined below when appropriate.
        
name = None
path = <property object at 0x7f75e2b31530>

              The sequence of directory path that a distribution finder
              should search.

              Typically refers to Python installed package paths such as
              "site-packages" directories and defaults to ``sys.path``.
            
find_distributions(self, context=<importlib.metadata.DistributionFinder.Context object at 0x7f75e2b0f8e0>)


          Find distributions.

          Return an iterable of all Distribution instances capable of
          loading the metadata for packages matching the ``context``,
          a DistributionFinder.Context instance.
        
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().
        

EntryPoint

An entry point as defined by Python packaging conventions.

    See `the packaging docs on entry points
    <https://packaging.python.org/specifications/entry-points/>`_
    for more information.

    >>> ep = EntryPoint(
    ...     name=None, group=None, value='package.module:attr [extra1, extra2]')
    >>> ep.module
    'package.module'
    >>> ep.attr
    'attr'
    >>> ep.extras
    ['extra1', 'extra2']
    
count(self, value, /)

  Return number of occurrences of value.
index(self, value, start=0, stop=9223372036854775807, /)

  Return first index of value.

  Raises ValueError if the value is not present.
load(self)

  Load the entry point from its definition. If only a module
          is indicated by the value, return that module. Otherwise,
          return the named object.
        
matches(self, **params)


          EntryPoint matches the given parameters.

          >>> ep = EntryPoint(group='foo', name='bar', value='bing:bong [extra1, extra2]')
          >>> ep.matches(group='foo')
          True
          >>> ep.matches(name='bar', value='bing:bong [extra1, extra2]')
          True
          >>> ep.matches(group='foo', name='other')
          False
          >>> ep.matches()
          True
          >>> ep.matches(extras=['extra1', 'extra2'])
          True
          >>> ep.matches(module='bing')
          True
          >>> ep.matches(attr='bong')
          True
        
attr = <property object at 0x7f75e2b30db0>
dist = None
extras = <property object at 0x7f75e2b30d60>
group = _tuplegetter(2, 'Alias for field number 2')
  Alias for field number 2
module = <property object at 0x7f75e2b30bd0>
name = _tuplegetter(0, 'Alias for field number 0')
  Alias for field number 0
pattern = re.compile('(?P<module>[\\w.]+)\\s*(:\\s*(?P<attr>[\\w.]+)\\s*)?((?P<extras>\\[.*\\])\\s*)?


)
value = _tuplegetter(1, 'Alias for field number 1')
  Alias for field number 1

EntryPoints


    An immutable collection of selectable EntryPoint objects.
    
append(self, *args, **kwargs)
clear(self, /)

  Remove all items from list.
copy(self, /)

  Return a shallow copy of the list.
count(self, value, /)

  Return number of occurrences of value.
extend(self, *args, **kwargs)
index(self, value, start=0, stop=9223372036854775807, /)

  Return first index of value.

  Raises ValueError if the value is not present.
insert(self, *args, **kwargs)
pop(self, *args, **kwargs)
remove(self, *args, **kwargs)
reverse(self, *args, **kwargs)
select(self, **params)


          Select entry points from self that match the
          given parameters (typically group and/or name).
        
sort(self, *args, **kwargs)
groups = <property object at 0x7f75e2b30f40>

          Return the set of all groups of all entry points.

          For coverage while SelectableGroups is present.
          >>> EntryPoints().groups
          set()
        
names = <property object at 0x7f75e2b30ef0>

          Return the set of all names of all entry points.
        

FastPath


    Micro-optimized class for searching a path for
    children.
    
children(self)
joinpath(self, child)
wrapper(self, *args, **kwargs)
search(self, name)
zip_children(self)
mtime = <property object at 0x7f75e2b31670>

FileHash

FreezableDefaultDict


    Often it is desirable to prevent the mutation of
    a default dict after its initial construction, such
    as to prevent mutation during iteration.

    >>> dd = FreezableDefaultDict(list)
    >>> dd[0].append('1')
    >>> dd.freeze()
    >>> dd[1]
    []
    >>> len(dd)
    1
    
clear(...)

  D.clear() -> None.  Remove all items from D.
copy(...)

  D.copy() -> a shallow copy of D.
freeze(self)
fromkeys(iterable, value=None, /)

  Create a new dictionary with keys from iterable and values set to value.
get(self, key, default=None, /)

  Return the value for key if key is in the dictionary, else default.
items(...)

  D.items() -> a set-like object providing a view on D's items
keys(...)

  D.keys() -> a set-like object providing a view on D's keys
pop(...)

  D.pop(k[,d]) -> v, remove specified key and return the corresponding value.

  If the key is not found, return the default if given; otherwise,
  raise a KeyError.
popitem(self, /)

  Remove and return a (key, value) pair as a 2-tuple.

  Pairs are returned in LIFO (last-in, first-out) order.
  Raises KeyError if the dict is empty.
setdefault(self, key, default=None, /)

  Insert key with a value of default if key is not in the dictionary.

  Return the value for key if key is in the dictionary, else default.
update(...)

  D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
  If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
  If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
  In either case, this is followed by: for k in F:  D[k] = F[k]
values(...)

  D.values() -> an object providing a view on D's values
default_factory = <member 'default_factory' of 'collections.defaultdict' objects>
  Factory for default value called by __missing__().

Lookup

search(self, prepared)

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().
        

MetadataPathFinder

invalidate_caches.Context


        Keyword arguments presented by the caller to
        ``distributions()`` or ``Distribution.discover()``
        to narrow the scope of a search for distributions
        in all DistributionFinders.

        Each DistributionFinder may expect any parameters
        and should attempt to honor the canonical
        parameters defined below when appropriate.
        
name = None
path = <property object at 0x7f75e2b31530>

              The sequence of directory path that a distribution finder
              should search.

              Typically refers to Python installed package paths such as
              "site-packages" directories and defaults to ``sys.path``.
            
find_distributions(context=<importlib.metadata.DistributionFinder.Context object at 0x7f75e2b0fc10>)


          Find distributions.

          Return an iterable of all Distribution instances capable of
          loading the metadata for packages matching ``context.name``
          (or all names if ``None`` indicated) along the paths in the list
          of directories ``context.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(cls)

PackageMetadata

get_all(self, name: str, failobj: ~_T = Ellipsis) -> Union[List[Any], ~_T]


          Return all values associated with a possibly multi-valued key.
        
json = <property object at 0x7f75e2b0a4d0>

          A JSON-compatible form of the metadata.
        

PackageNotFoundError

The package was not found.
with_traceback(...)

  Exception.with_traceback(tb) --
      set self.__traceback__ to tb and return self.
args = <attribute 'args' of 'BaseException' objects>
msg = <member 'msg' of 'ImportError' objects>
  exception message
name = <property object at 0x7f75e2d63ce0>
path = <member 'path' of 'ImportError' objects>
  module path

PackagePath

A reference to a path in a package
as_posix(self)

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

  Return the path as a 'file' URI.
is_absolute(self)

  True if the path is absolute (has both a root and, if applicable,
          a drive).
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.
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).
        
locate(self)

  Return a path-like object for this path
match(self, path_pattern)


          Return True if this path matches the given pattern.
        
read_binary(self)
read_text(self, encoding='utf-8')
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.
        
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.
        
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']
        

Pair

count(self, value, /)

  Return number of occurrences of value.
index(self, value, start=0, stop=9223372036854775807, /)

  Return first index of value.

  Raises ValueError if the value is not present.
parse(text)
name = _tuplegetter(0, 'Alias for field number 0')
  Alias for field number 0
value = _tuplegetter(1, 'Alias for field number 1')
  Alias for field number 1

PathDistribution

at(path)

  Return a Distribution for the indicated metadata path

          :param path: a string or path-like object
          :return: a concrete Distribution instance for the path
        
discover(**kwargs)

  Return an iterable of Distribution objects for all packages.

          Pass a ``context`` or pass keyword arguments for constructing
          a context.

          :context: A ``DistributionFinder.Context`` object.
          :return: Iterable of Distribution objects for all packages.
        
from_name(name)

  Return the Distribution for the given package name.

          :param name: The name of the distribution package to search for.
          :return: The Distribution instance (or subclass thereof) for the named
              package, if found.
          :raises PackageNotFoundError: When the named package's distribution
              metadata cannot be found.
        
locate_file(self, path)
read_text(self, filename)

  Attempt to load metadata file given by the name.

          :param filename: The name of the file in the distribution info.
          :return: The text if found, otherwise None.
        
entry_points = <property object at 0x7f75e2b313f0>
files = <property object at 0x7f75e2b31440>
  Files in this distribution.

          :return: List of PackagePath for this distribution or None

          Result is `None` if the metadata file that enumerates files
          (i.e. RECORD for dist-info or SOURCES.txt for egg-info) is
          missing.
          Result may be empty if the metadata exists but is empty.
        
metadata = <property object at 0x7f75e2b312b0>
  Return the parsed metadata for this Distribution.

          The returned object will have keys that name the various bits of
          metadata.  See PEP 566 for details.
        
name = <property object at 0x7f75e2b31300>
  Return the 'Name' metadata for the distribution package.
requires = <property object at 0x7f75e2b31490>
  Generated requirements specified for this Distribution
version = <property object at 0x7f75e2b313a0>
  Return the 'Version' metadata for the distribution package.

Prepared


    A prepared search for metadata on a possibly-named package.
    
legacy_normalize(name)


          Normalize the package name as found in the convention in
          older packaging tools versions and specs.
        
normalize(name)


          PEP 503 normalization plus dashes as underscores.
        
legacy_normalized = None
normalized = None

Sectioned


    A simple entry point config parser for performance

    >>> for item in Sectioned.read(Sectioned._sample):
    ...     print(item)
    Pair(name='sec1', value='# comments ignored')
    Pair(name='sec1', value='a = 1')
    Pair(name='sec1', value='b = 2')
    Pair(name='sec2', value='a = 2')

    >>> res = Sectioned.section_pairs(Sectioned._sample)
    >>> item = next(res)
    >>> item.name
    'sec1'
    >>> item.value
    Pair(name='a', value='1')
    >>> item = next(res)
    >>> item.value
    Pair(name='b', value='2')
    >>> item = next(res)
    >>> item.name
    'sec2'
    >>> item.value
    Pair(name='a', value='2')
    >>> list(res)
    []
    
read(text, filter_=None)
section_pairs(text)
valid(line)

SelectableGroups


    A backward- and forward-compatible result from
    entry_points that fully implements the dict interface.
    
clear(...)

  D.clear() -> None.  Remove all items from D.
copy(...)

  D.copy() -> a shallow copy of D
fromkeys(iterable, value=None, /)

  Create a new dictionary with keys from iterable and values set to value.
get(self, name, default=None)
items(...)

  D.items() -> a set-like object providing a view on D's items
keys(self)
load(eps)
pop(...)

  D.pop(k[,d]) -> v, remove specified key and return the corresponding value.

  If the key is not found, return the default if given; otherwise,
  raise a KeyError.
popitem(self, /)

  Remove and return a (key, value) pair as a 2-tuple.

  Pairs are returned in LIFO (last-in, first-out) order.
  Raises KeyError if the dict is empty.
select(self, **params)
setdefault(self, key, default=None, /)

  Insert key with a value of default if key is not in the dictionary.

  Return the value for key if key is in the dictionary, else default.
update(...)

  D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
  If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
  If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
  In either case, this is followed by: for k in F:  D[k] = F[k]
values(self)
groups = <property object at 0x7f75e2b31120>
names = <property object at 0x7f75e2b31170>

          for coverage:
          >>> SelectableGroups().names
          set()
        

SimplePath


    A minimal subset of pathlib.Path required by PathDistribution.
    
joinpath(self) -> 'SimplePath'
parent(self) -> 'SimplePath'
read_text(self) -> str

starmap

Return an iterator whose values are returned from the function evaluated with an argument tuple taken from the given sequence.

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

distribution

distribution(distribution_name)

  Get the ``Distribution`` instance for the named package.

      :param distribution_name: The name of the distribution package as a string.
      :return: A ``Distribution`` instance (or subclass thereof).
    

distributions

distributions(**kwargs)

  Get all ``Distribution`` instances in the current environment.

      :return: An iterable of ``Distribution`` instances.
    

entry_points

entry_points(**params) -> Union[importlib.metadata.EntryPoints, importlib.metadata.SelectableGroups]

  Return EntryPoint objects for all installed packages.

      Pass selection parameters (group or name) to filter the
      result to entry points matching those properties (see
      EntryPoints.select()).

      For compatibility, returns ``SelectableGroups`` object unless
      selection parameters are supplied. In the future, this function
      will return ``EntryPoints`` instead of ``SelectableGroups``
      even when no selection parameters are supplied.

      For maximum future compatibility, pass selection parameters
      or invoke ``.select`` with parameters on the result.

      :return: EntryPoints or SelectableGroups for all installed packages.
    

files

files(distribution_name)

  Return a list of files for the named package.

      :param distribution_name: The name of the distribution package to query.
      :return: List of files composing the distribution.
    

import_module

import_module(name, package=None)

  Import a module.

      The 'package' argument is required when performing a relative import. It
      specifies the package to use as the anchor point from which to resolve the
      relative import to an absolute import.

    

metadata

metadata(distribution_name) -> importlib.metadata._meta.PackageMetadata

  Get the metadata for the named package.

      :param distribution_name: The name of the distribution package to query.
      :return: A PackageMetadata containing the parsed metadata.
    

method_cache

method_cache(method, cache_wrapper=None)


      Wrap lru_cache to support storing the cache data in the object instances.

      Abstracts the common paradigm where the method explicitly saves an
      underscore-prefixed protected property on first call and returns that
      subsequently.

      >>> class MyClass:
      ...     calls = 0
      ...
      ...     @method_cache
      ...     def method(self, value):
      ...         self.calls += 1
      ...         return value

      >>> a = MyClass()
      >>> a.method(3)
      3
      >>> for x in range(75):
      ...     res = a.method(x)
      >>> a.calls
      75

      Note that the apparent behavior will be exactly like that of lru_cache
      except that the cache is stored on each instance, so values in one
      instance will not flush values from another, and when an instance is
      deleted, so are the cached values for that instance.

      >>> b = MyClass()
      >>> for x in range(35):
      ...     res = b.method(x)
      >>> b.calls
      35
      >>> a.method(0)
      0
      >>> a.calls
      75

      Note that if method had been decorated with ``functools.lru_cache()``,
      a.calls would have been 76 (due to the cached value of 0 having been
      flushed by the 'b' instance).

      Clear the cache with ``.cache_clear()``

      >>> a.method.cache_clear()

      Same for a method that hasn't yet been called.

      >>> c = MyClass()
      >>> c.method.cache_clear()

      Another cache wrapper may be supplied:

      >>> cache = functools.lru_cache(maxsize=2)
      >>> MyClass.method2 = method_cache(lambda self: 3, cache_wrapper=cache)
      >>> a = MyClass()
      >>> a.method2()
      3

      Caution - do not subsequently wrap the method with another decorator, such
      as ``@property``, which changes the semantics of the function.

      See also
      http://code.activestate.com/recipes/577452-a-memoize-decorator-for-instance-methods/
      for another implementation and additional justification.
    

packages_distributions

packages_distributions() -> Mapping[str, List[str]]


      Return a mapping of top-level packages to their
      distributions.

      >>> import collections.abc
      >>> pkgs = packages_distributions()
      >>> all(isinstance(dist, collections.abc.Sequence) for dist in pkgs.values())
      True
    

requires

requires(distribution_name)


      Return a list of requirements for the named package.

      :return: An iterator of requirements, suitable for
          packaging.requirement.Requirement.
    

unique_everseen

unique_everseen(iterable, key=None)

  List unique elements, preserving order. Remember all elements ever seen.

version

version(distribution_name)

  Get the version string for the named package.

      :param distribution_name: The name of the distribution package to query.
      :return: The version string for the package as defined in the package's
          "Version" metadata key.
    

Other members

List = typing.List
  A generic version of list.
Mapping = typing.Mapping
  A generic version of collections.abc.Mapping.
Optional = typing.Optional
  Optional type.

      Optional[X] is equivalent to Union[X, None].
    
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

abc

collections

csv

email

functools

itertools

operator

os

pathlib

posixpath

re

sys

textwrap

warnings

zipfile