Skip to content

Commit 741d554

Browse files
email.utils: raise TypeError for non-string non-3-tuple, update docs
Revised per reviewer feedback: instead of silently handling non-3-tuples, raise TypeError with a clear message. Updated docs to say 'not a 3-tuple' instead of 'not a tuple' to match the code's actual check.
1 parent d85561d commit 741d554

File tree

3 files changed

+10
-9
lines changed

3 files changed

+10
-9
lines changed

Doc/library/email.utils.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,7 @@ of the new API.
212212
:rfc:`2231` header is not known by Python; it defaults to ``'us-ascii'``.
213213

214214
For convenience, if the *value* passed to :func:`collapse_rfc2231_value` is not
215-
a tuple, it should be a string and it is returned unquoted.
215+
a 3-tuple, it should be a string and it is returned unquoted.
216216

217217

218218
.. function:: decode_params(params)

Lib/email/utils.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -449,8 +449,10 @@ def decode_params(params):
449449
def collapse_rfc2231_value(value, errors='replace',
450450
fallback_charset='us-ascii'):
451451
if not isinstance(value, tuple) or len(value) != 3:
452-
if isinstance(value, tuple):
453-
return str(value)
452+
if not isinstance(value, str):
453+
raise TypeError(
454+
f"expected str or 3-tuple, got {type(value).__name__}"
455+
)
454456
return unquote(value)
455457
# While value comes to us as a unicode string, we need it to be a bytes
456458
# object. We do not want bytes() normal utf-8 decoder, we want a straight

Lib/test/test_email/test_email.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5790,14 +5790,13 @@ def test_should_not_hang_on_invalid_ew_messages(self):
57905790
msg = email.message_from_string(m)
57915791

57925792
def test_collapse_rfc2231_value_non_3_tuple(self):
5793-
# collapse_rfc2231_value should not crash on tuples
5794-
# whose length is not 3.
5793+
# collapse_rfc2231_value raises TypeError on values that are
5794+
# neither a string nor a 3-tuple.
57955795
from email.utils import collapse_rfc2231_value
5796-
# Non-3-tuples should return a string, not raise AttributeError.
5797-
for val in [(), ('a',), ('a', 'b'), ('a', 'b', 'c', 'd')]:
5796+
for val in [(), ('a',), ('a', 'b'), ('a', 'b', 'c', 'd'), 42, None]:
57985797
with self.subTest(val=val):
5799-
result = collapse_rfc2231_value(val)
5800-
self.assertIsInstance(result, str)
5798+
with self.assertRaises(TypeError):
5799+
collapse_rfc2231_value(val)
58015800
# A proper 3-tuple decodes correctly.
58025801
result = collapse_rfc2231_value(('us-ascii', 'en', 'hello'))
58035802
self.assertEqual(result, 'hello')

0 commit comments

Comments
 (0)