diff --git a/Lib/_pyio.py b/Lib/_pyio.py index 9d1cf209622320..3d30c17144978a 100644 --- a/Lib/_pyio.py +++ b/Lib/_pyio.py @@ -2778,7 +2778,8 @@ def readline(self, size=None): @property def newlines(self): - return self._decoder.newlines if self._decoder else None + # Without universal newlines, the decoder has no newlines attribute. + return getattr(self._decoder, "newlines", None) def _dealloc_warn(self, source): if dealloc_warn := getattr(self.buffer, "_dealloc_warn", None): diff --git a/Lib/test/test_io/test_memoryio.py b/Lib/test/test_io/test_memoryio.py index 20c2777b6c3ce0..f6dbd22a3bde9f 100644 --- a/Lib/test/test_io/test_memoryio.py +++ b/Lib/test/test_io/test_memoryio.py @@ -799,6 +799,12 @@ def force_decode(): force_decode() self.assertEqual(memio.newlines, ("\r", "\n", "\r\n")) + def test_newlines_property_without_universal_newlines(self): + for newline in ("\n", "\r", "\r\n"): + memio = self.ioclass("a\r\nb\rc\n", newline=newline) + memio.read() + self.assertIsNone(memio.newlines) + def test_relative_seek(self): memio = self.ioclass() diff --git a/Lib/test/test_io/test_textio.py b/Lib/test/test_io/test_textio.py index 246b2dc6087bd3..e980ed9db06a2d 100644 --- a/Lib/test/test_io/test_textio.py +++ b/Lib/test/test_io/test_textio.py @@ -458,6 +458,8 @@ def test_newlines_input(self): buf = self.BytesIO(testdata) txt = self.TextIOWrapper(buf, encoding="ascii", newline=newline) self.assertEqual(txt.readlines(), expected) + self.assertEqual(txt.newlines, + None if newline else ("\r", "\n", "\r\n")) txt.seek(0) self.assertEqual(txt.read(), "".join(expected)) diff --git a/Misc/NEWS.d/next/Library/2026-12-04-10-42-37.gh-issue-163135.qpziIg.rst b/Misc/NEWS.d/next/Library/2026-12-04-10-42-37.gh-issue-163135.qpziIg.rst new file mode 100644 index 00000000000000..a9eba8dae63b74 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-12-04-10-42-37.gh-issue-163135.qpziIg.rst @@ -0,0 +1,3 @@ +Fix :attr:`!_pyio.TextIOWrapper.newlines` raising :exc:`AttributeError` +instead of returning ``None`` when *newline* is ``'\n'``, ``'\r'`` or +``'\r\n'``.