Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Raise KeyError when requesting a metadata value that doesn't exist #416

Merged
merged 3 commits into from Dec 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 15 additions & 0 deletions CHANGES.rst
@@ -1,3 +1,18 @@
v6.0.0
======

* #371: When a key is missing from metadata, raise a ``KeyError``
instead of returning ``None``, matching the usual expectation for
mapping objects and also the protocol definition.

Projects should update to expect the ``KeyError`` or wrap the call
to replace a ``KeyError`` with a ``None`` return, e.g.::

try:
value = metadata(pkg)['Name']
except KeyError:
value = None

v5.1.0
======

Expand Down
14 changes: 14 additions & 0 deletions importlib_metadata/_adapters.py
Expand Up @@ -39,6 +39,20 @@ def __init__(self, *args, **kwargs):
def __iter__(self):
return super().__iter__()

def __getitem__(self, item):
"""
Prefer dict-like behavior for __getitem__ when keys are missing.
>>> msg = Message(email.message.Message())
>>> msg['thing']
Traceback (most recent call last):
...
KeyError: 'thing'
"""
res = super().__getitem__(item)
if res is None:
raise KeyError(item)
return res

def _repair_headers(self):
def redent(value):
"Correct for RFC822 indentation"
Expand Down
8 changes: 8 additions & 0 deletions tests/test_api.py
Expand Up @@ -141,6 +141,14 @@ def test_importlib_metadata_version(self):
resolved = version('importlib-metadata')
assert re.match(self.version_pattern, resolved)

def test_missing_key(self):
"""
Attempting to request missing metadata raises KeyError.
"""
md = metadata('distinfo-pkg')
with self.assertRaises(KeyError):
md['does-not-exist']

@staticmethod
def _test_files(files):
root = files[0].root
Expand Down