]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-17735: inspect.findsource now raises OSError when co_lineno is out of range ...
authorIrit Katriel <iritkatriel@yahoo.com>
Fri, 4 Dec 2020 21:22:03 +0000 (21:22 +0000)
committerGitHub <noreply@github.com>
Fri, 4 Dec 2020 21:22:03 +0000 (23:22 +0200)
This can happen when a file was edited after it was imported.

Lib/inspect.py
Lib/test/test_inspect.py
Misc/NEWS.d/next/Library/2020-12-03-22-22-24.bpo-17735.Qsaaue.rst [new file with mode: 0644]

index 073a79d97acd2d0c780de2a34fa7bf0f67bc579b..9150ac104dcb73a5fa9cb83922ce953c511493ef 100644 (file)
@@ -868,7 +868,12 @@ def findsource(object):
         lnum = object.co_firstlineno - 1
         pat = re.compile(r'^(\s*def\s)|(\s*async\s+def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
         while lnum > 0:
-            if pat.match(lines[lnum]): break
+            try:
+                line = lines[lnum]
+            except IndexError:
+                raise OSError('lineno is out of bounds')
+            if pat.match(line):
+                break
             lnum = lnum - 1
         return lines, lnum
     raise OSError('could not find code object')
index 172e6bf6cd8a637443e91ce835f0baddc80a08ea..c81d828b57ece9aba18f6f6672810ff5f9d3f42b 100644 (file)
@@ -712,6 +712,17 @@ class TestBuggyCases(GetSourceBase):
             self.assertRaises(IOError, inspect.findsource, co)
             self.assertRaises(IOError, inspect.getsource, co)
 
+    def test_findsource_with_out_of_bounds_lineno(self):
+        mod_len = len(inspect.getsource(mod))
+        src = '\n' * 2* mod_len + "def f(): pass"
+        co = compile(src, mod.__file__, "exec")
+        g, l = {}, {}
+        eval(co, g, l)
+        func = l['f']
+        self.assertEqual(func.__code__.co_firstlineno, 1+2*mod_len)
+        with self.assertRaisesRegex(IOError, "lineno is out of bounds"):
+            inspect.findsource(func)
+
     def test_getsource_on_method(self):
         self.assertSourceEqual(mod2.ClassWithMethod.method, 118, 119)
 
diff --git a/Misc/NEWS.d/next/Library/2020-12-03-22-22-24.bpo-17735.Qsaaue.rst b/Misc/NEWS.d/next/Library/2020-12-03-22-22-24.bpo-17735.Qsaaue.rst
new file mode 100644 (file)
index 0000000..655781e
--- /dev/null
@@ -0,0 +1,4 @@
+:func:`inspect.findsource` now raises :exc:`OSError` instead of
+:exc:`IndexError` when :attr:`co_lineno` of a code object is greater than the
+file length. This can happen, for example, when a file is edited after it was
+imported.  PR by Irit Katriel.