Skip to content

Commit d16c9d1

Browse files
gh-116987: Support class code objects in inspect.findsource() (GH-117025)
1 parent 6547330 commit d16c9d1

File tree

4 files changed

+11
-9
lines changed

4 files changed

+11
-9
lines changed

Lib/inspect.py

+2-9
Original file line numberDiff line numberDiff line change
@@ -1157,15 +1157,8 @@ def findsource(object):
11571157
if not hasattr(object, 'co_firstlineno'):
11581158
raise OSError('could not find function definition')
11591159
lnum = object.co_firstlineno - 1
1160-
pat = re.compile(r'^(\s*def\s)|(\s*async\s+def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
1161-
while lnum > 0:
1162-
try:
1163-
line = lines[lnum]
1164-
except IndexError:
1165-
raise OSError('lineno is out of bounds')
1166-
if pat.match(line):
1167-
break
1168-
lnum = lnum - 1
1160+
if lnum >= len(lines):
1161+
raise OSError('lineno is out of bounds')
11691162
return lines, lnum
11701163
raise OSError('could not find code object')
11711164

Lib/test/test_inspect/inspect_fodder2.py

+5
Original file line numberDiff line numberDiff line change
@@ -310,3 +310,8 @@ def f():
310310
class cls310:
311311
def g():
312312
pass
313+
314+
# line 314
315+
class ClassWithCodeObject:
316+
import sys
317+
code = sys._getframe(0).f_code

Lib/test/test_inspect/test_inspect.py

+3
Original file line numberDiff line numberDiff line change
@@ -983,6 +983,9 @@ def test_findsource_with_out_of_bounds_lineno(self):
983983
def test_getsource_on_method(self):
984984
self.assertSourceEqual(mod2.ClassWithMethod.method, 118, 119)
985985

986+
def test_getsource_on_class_code_object(self):
987+
self.assertSourceEqual(mod2.ClassWithCodeObject.code, 315, 317)
988+
986989
def test_nested_func(self):
987990
self.assertSourceEqual(mod2.cls135.func136, 136, 139)
988991

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

0 commit comments

Comments
 (0)