Skip to content

Commit 4fe7502

Browse files
authored
Merge pull request #417 from python/debt/deprecate-getitem-none
Mark `PackageMetadata.__getitem__` as deprecated for missing values
2 parents 747e081 + 880a621 commit 4fe7502

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed

CHANGES.rst

+7
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,10 @@
1+
v5.2.0
2+
======
3+
4+
* #371: Deprecated expectation that ``PackageMetadata.__getitem__``
5+
will return ``None`` for missing keys. In the future, it will raise a
6+
``KeyError``.
7+
18
v5.1.0
29
======
310

importlib_metadata/_adapters.py

+22
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,20 @@
1+
import functools
2+
import warnings
13
import re
24
import textwrap
35
import email.message
46

57
from ._text import FoldedCase
8+
from ._compat import pypy_partial
9+
10+
11+
# Do not remove prior to 2024-01-01 or Python 3.14
12+
_warn = functools.partial(
13+
warnings.warn,
14+
"Implicit None on return values is deprecated and will raise KeyErrors.",
15+
DeprecationWarning,
16+
stacklevel=pypy_partial(2),
17+
)
618

719

820
class Message(email.message.Message):
@@ -39,6 +51,16 @@ def __init__(self, *args, **kwargs):
3951
def __iter__(self):
4052
return super().__iter__()
4153

54+
def __getitem__(self, item):
55+
"""
56+
Warn users that a ``KeyError`` can be expected when a
57+
mising key is supplied. Ref python/importlib_metadata#371.
58+
"""
59+
res = super().__getitem__(item)
60+
if res is None:
61+
_warn()
62+
return res
63+
4264
def _repair_headers(self):
4365
def redent(value):
4466
"Correct for RFC822 indentation"

tests/test_api.py

+8
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,14 @@ def test_importlib_metadata_version(self):
141141
resolved = version('importlib-metadata')
142142
assert re.match(self.version_pattern, resolved)
143143

144+
def test_missing_key_legacy(self):
145+
"""
146+
Requesting a missing key will still return None, but warn.
147+
"""
148+
md = metadata('distinfo-pkg')
149+
with suppress_known_deprecation():
150+
assert md['does-not-exist'] is None
151+
144152
@staticmethod
145153
def _test_files(files):
146154
root = files[0].root

0 commit comments

Comments
 (0)