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

Mark PackageMetadata.__getitem__ as deprecated for missing values #417

Merged
merged 1 commit 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
7 changes: 7 additions & 0 deletions CHANGES.rst
@@ -1,3 +1,10 @@
v5.2.0
======

* #371: Deprecated expectation that ``PackageMetadata.__getitem__``
will return ``None`` for missing keys. In the future, it will raise a
``KeyError``.

v5.1.0
======

Expand Down
22 changes: 22 additions & 0 deletions importlib_metadata/_adapters.py
@@ -1,8 +1,20 @@
import functools
import warnings
import re
import textwrap
import email.message

from ._text import FoldedCase
from ._compat import pypy_partial


# Do not remove prior to 2024-01-01 or Python 3.14
_warn = functools.partial(
warnings.warn,
"Implicit None on return values is deprecated and will raise KeyErrors.",
DeprecationWarning,
stacklevel=pypy_partial(2),
)


class Message(email.message.Message):
Expand Down Expand Up @@ -39,6 +51,16 @@ def __init__(self, *args, **kwargs):
def __iter__(self):
return super().__iter__()

def __getitem__(self, item):
"""
Warn users that a ``KeyError`` can be expected when a
mising key is supplied. Ref python/importlib_metadata#371.
"""
res = super().__getitem__(item)
if res is None:
_warn()
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_legacy(self):
"""
Requesting a missing key will still return None, but warn.
"""
md = metadata('distinfo-pkg')
with suppress_known_deprecation():
assert md['does-not-exist'] is None

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