https://github.com/python/cpython/commit/e7c5f60efc149dda3d3592fa2001f4583b128512
commit: e7c5f60efc149dda3d3592fa2001f4583b128512
branch: main
author: Adam Turner <[email protected]>
committer: AA-Turner <[email protected]>
date: 2025-04-19T16:18:03+01:00
summary:
gh-130167: Improve the error case for ``textwrap.dedent`` (#132666)
files:
M Lib/test/test_textwrap.py
M Lib/textwrap.py
M Misc/NEWS.d/3.14.0a7.rst
diff --git a/Lib/test/test_textwrap.py b/Lib/test/test_textwrap.py
index 77366988b57fa7..cbd383ea4e2656 100644
--- a/Lib/test/test_textwrap.py
+++ b/Lib/test/test_textwrap.py
@@ -765,6 +765,13 @@ def test_subsequent_indent(self):
# of IndentTestCase!
class DedentTestCase(unittest.TestCase):
+ def test_type_error(self):
+ with self.assertRaisesRegex(TypeError, "expected str object, not"):
+ dedent(0)
+
+ with self.assertRaisesRegex(TypeError, "expected str object, not"):
+ dedent(b'')
+
def assertUnchanged(self, text):
"""assert that dedent() has no effect on 'text'"""
self.assertEqual(text, dedent(text))
diff --git a/Lib/textwrap.py b/Lib/textwrap.py
index bac98c99e41df8..00465f67d0941a 100644
--- a/Lib/textwrap.py
+++ b/Lib/textwrap.py
@@ -426,10 +426,11 @@ def dedent(text):
Entirely blank lines are normalized to a newline character.
"""
- if not text:
- return text
-
- lines = text.split('\n')
+ try:
+ lines = text.split('\n')
+ except (AttributeError, TypeError):
+ msg = f'expected str object, not {type(text).__qualname__!r}'
+ raise TypeError(msg) from None
# Get length of leading whitespace, inspired by ``os.path.commonprefix()``.
non_blank_lines = [l for l in lines if l and not l.isspace()]
diff --git a/Misc/NEWS.d/3.14.0a7.rst b/Misc/NEWS.d/3.14.0a7.rst
index 900cde10641978..35b96d33da4175 100644
--- a/Misc/NEWS.d/3.14.0a7.rst
+++ b/Misc/NEWS.d/3.14.0a7.rst
@@ -288,7 +288,7 @@ Improve the import time of the :mod:`ast` module by
extracting the
.. nonce: 8M-HVz
.. section: Library
-Improved performance of :func:`textwrap.dedent` by an average of ~1.3x.
+Improved performance of :func:`textwrap.indent` by an average of ~1.3x.
Patch by Adam Turner.
..
_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-checkins.python.org/
Member address: [email protected]