Skip to content

[3.8] bpo-17735: inspect.findsource now raises OSError when co_lineno is out of range (GH-23633) #23647

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 4, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion Lib/inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -837,7 +837,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')
Expand Down
11 changes: 11 additions & 0 deletions Lib/test/test_inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -713,6 +713,17 @@ def test_findsource_without_filename(self):
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)

Expand Down
Original file line number Diff line number Diff line change
@@ -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.