Skip to content

Properly break exception chain in importlib.metadata.Distribution.from_name() #140141

@bswck

Description

@bswck

Bug report

Bug description:

>>> import importlib.metadata
>>> importlib.metadata.distribution("-")
Traceback (most recent call last):
  File ".\Lib\importlib\metadata\__init__.py", line 458, in from_name
    return next(iter(cls._prefer_valid(cls.discover(name=name))))
StopIteration

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<python-input-1>", line 1, in <module>
    importlib.metadata.distribution("-")
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^
  File ".\Lib\importlib\metadata\__init__.py", line 1032, in distribution
    return Distribution.from_name(distribution_name)
           ~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^
  File ".\Lib\importlib\metadata\__init__.py", line 460, in from_name
    raise PackageNotFoundError(name)
importlib.metadata.PackageNotFoundError: No package metadata was found for -

This message is somewhat incorrect and can be much shorter. PackageNotFoundError is the interesting exception, while StopIteration is just an implementation detail, so there's no need to include the latter.

Instead, I'd expect:

>>> import importlib.metadata
>>> importlib.metadata.distribution("-")
Traceback (most recent call last):
  File "<python-input-1>", line 1, in <module>
    importlib.metadata.distribution("-")
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^
  File ".\Lib\importlib\metadata\__init__.py", line 1032, in distribution
    return Distribution.from_name(distribution_name)
           ~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^
  File ".\Lib\importlib\metadata\__init__.py", line 460, in from_name
    raise PackageNotFoundError(name) from None
importlib.metadata.PackageNotFoundError: No package metadata was found for -

It contains everything necessary for this specific traceback.

CPython versions tested on:

CPython main branch

Operating systems tested on:

Windows

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytopic-importlibtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions