gh-116987: Support class code objects in inspect.findsource() (GH-117025)

This commit is contained in:
Tian Gao 2024-03-21 03:30:10 -07:00 committed by GitHub
parent 6547330f4e
commit d16c9d1278
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 11 additions and 9 deletions

View File

@ -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')

View File

@ -310,3 +310,8 @@ else:
class cls310:
def g():
pass
# line 314
class ClassWithCodeObject:
import sys
code = sys._getframe(0).f_code

View File

@ -983,6 +983,9 @@ class TestBuggyCases(GetSourceBase):
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)

View File

@ -0,0 +1 @@
Fixed :func:`inspect.findsource` for class code objects.