]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-130167: Improve the error case for ``textwrap.dedent`` (#132666)
authorAdam Turner <9087854+AA-Turner@users.noreply.github.com>
Sat, 19 Apr 2025 15:18:03 +0000 (16:18 +0100)
committerGitHub <noreply@github.com>
Sat, 19 Apr 2025 15:18:03 +0000 (16:18 +0100)
Lib/test/test_textwrap.py
Lib/textwrap.py
Misc/NEWS.d/3.14.0a7.rst

index 77366988b57fa750ad28d4b42689a5f6e573b106..cbd383ea4e2656196d721de5ca5ec5308cd00569 100644 (file)
@@ -765,6 +765,13 @@ some (including a hanging indent).'''
 # 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))
index bac98c99e41df8474d2d39be137b8b7d2fc8c081..00465f67d0941a70f885eca09e772309a7e49e9e 100644 (file)
@@ -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()]
index 900cde10641978e8dbc0971b5eaece9c5fba43c7..35b96d33da4175d00112f4eca27651448514616b 100644 (file)
@@ -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.
 
 ..