Skip to content

gh-116987: Remove re pattern check in inspect.findsource as it's not needed anymore #117025

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
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
11 changes: 2 additions & 9 deletions Lib/inspect.py
Original file line number Diff line number Diff line change
@@ -1157,15 +1157,8 @@ def findsource(object):
if not hasattr(object, 'co_firstlineno'):
raise OSError('could not find function definition')
lnum = object.co_firstlineno - 1
pat = re.compile(r'^(\s*def\s)|(\s*async\s+def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
while lnum > 0:
try:
line = lines[lnum]
except IndexError:
raise OSError('lineno is out of bounds')
if pat.match(line):
break
lnum = lnum - 1
if lnum >= len(lines):
raise OSError('lineno is out of bounds')
return lines, lnum
raise OSError('could not find code object')

5 changes: 5 additions & 0 deletions Lib/test/test_inspect/inspect_fodder2.py
Original file line number Diff line number Diff line change
@@ -310,3 +310,8 @@ def f():
class cls310:
def g():
pass

# line 314
class ClassWithCodeObject:
import sys
code = sys._getframe(0).f_code
3 changes: 3 additions & 0 deletions Lib/test/test_inspect/test_inspect.py
Original file line number Diff line number Diff line change
@@ -983,6 +983,9 @@ def test_findsource_with_out_of_bounds_lineno(self):
def test_getsource_on_method(self):
self.assertSourceEqual(mod2.ClassWithMethod.method, 118, 119)

def test_getsource_on_class_code_object(self):
self.assertSourceEqual(mod2.ClassWithCodeObject.code, 315, 317)

def test_nested_func(self):
self.assertSourceEqual(mod2.cls135.func136, 136, 139)

Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed :func:`inspect.findsource` for class code objects.
Loading