diff options
author | Irit Katriel <iritkatriel@yahoo.com> | 2020-12-04 21:22:03 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-12-04 21:22:03 (GMT) |
commit | 2e0760bb2edb595050aff82f236cd32b44d3dfb3 (patch) | |
tree | efc0a4ef54bbebff196efd1d4d9e984f91a62832 /Lib | |
parent | 8d4f57dbd10846ffb4881b6509a511be0ab3b913 (diff) | |
download | cpython-2e0760bb2edb595050aff82f236cd32b44d3dfb3.zip cpython-2e0760bb2edb595050aff82f236cd32b44d3dfb3.tar.gz cpython-2e0760bb2edb595050aff82f236cd32b44d3dfb3.tar.bz2 |
bpo-17735: inspect.findsource now raises OSError when co_lineno is out of range (GH-23633)
This can happen when a file was edited after it was imported.
Diffstat (limited to 'Lib')
-rw-r--r-- | Lib/inspect.py | 7 | ||||
-rw-r--r-- | Lib/test/test_inspect.py | 11 |
2 files changed, 17 insertions, 1 deletions
diff --git a/Lib/inspect.py b/Lib/inspect.py index 073a79d..9150ac1 100644 --- a/Lib/inspect.py +++ b/Lib/inspect.py @@ -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') diff --git a/Lib/test/test_inspect.py b/Lib/test/test_inspect.py index 172e6bf..c81d828 100644 --- a/Lib/test/test_inspect.py +++ b/Lib/test/test_inspect.py @@ -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) |