Skip to content

Commit 20b8c9e

Browse files
gh-92336: linecache.getline should not raise exceptions on decoding errors (GH-94410)
(cherry picked from commit 21cbdae) Co-authored-by: Irit Katriel <[email protected]>
1 parent c5ecfa0 commit 20b8c9e

File tree

3 files changed

+8
-7
lines changed

3 files changed

+8
-7
lines changed

Lib/linecache.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ def updatecache(filename, module_globals=None):
135135
try:
136136
with tokenize.open(fullname) as fp:
137137
lines = fp.readlines()
138-
except OSError:
138+
except (OSError, UnicodeDecodeError, SyntaxError):
139139
return []
140140
if lines and not lines[-1].endswith('\n'):
141141
lines[-1] += '\n'

Lib/test/test_linecache.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -73,12 +73,10 @@ class GetLineTestsBadData(TempFile):
7373
# file_byte_string = b'Bad data goes here'
7474

7575
def test_getline(self):
76-
self.assertRaises((SyntaxError, UnicodeDecodeError),
77-
linecache.getline, self.file_name, 1)
76+
self.assertEqual(linecache.getline(self.file_name, 1), '')
7877

7978
def test_getlines(self):
80-
self.assertRaises((SyntaxError, UnicodeDecodeError),
81-
linecache.getlines, self.file_name)
79+
self.assertEqual(linecache.getlines(self.file_name), [])
8280

8381

8482
class EmptyFile(GetLineTestsGoodData, unittest.TestCase):
@@ -92,9 +90,11 @@ class SingleEmptyLine(GetLineTestsGoodData, unittest.TestCase):
9290
class GoodUnicode(GetLineTestsGoodData, unittest.TestCase):
9391
file_list = [\n', 'b\n', 'abcdef\n', 'ááááá\n']
9492

93+
class BadUnicode_NoDeclaration(GetLineTestsBadData, unittest.TestCase):
94+
file_byte_string = b'\n\x80abc'
9595

96-
class BadUnicode(GetLineTestsBadData, unittest.TestCase):
97-
file_byte_string = b'\x80abc'
96+
class BadUnicode_WithDeclaration(GetLineTestsBadData, unittest.TestCase):
97+
file_byte_string = b'# coding=utf-8\n\x80abc'
9898

9999

100100
class LineCacheTests(unittest.TestCase):
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix bug where :meth:`linecache.getline` fails on bad files with :exc:`UnicodeDecodeError` or :exc:`SyntaxError`. It now returns an empty string as per the documentation.

0 commit comments

Comments
 (0)