]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-116987: Support class code objects in inspect.findsource() (GH-117025)
authorTian Gao <gaogaotiantian@hotmail.com>
Thu, 21 Mar 2024 10:30:10 +0000 (03:30 -0700)
committerGitHub <noreply@github.com>
Thu, 21 Mar 2024 10:30:10 +0000 (10:30 +0000)
Lib/inspect.py
Lib/test/test_inspect/inspect_fodder2.py
Lib/test/test_inspect/test_inspect.py
Misc/NEWS.d/next/Library/2024-03-19-19-42-25.gh-issue-116987.ZVKUH1.rst [new file with mode: 0644]

index 7336cea0dc3fdc2dc9dd2e6965681dc59d5f37b4..422c09a92ad141705bcb7cfdf76d6a5c88aa0a1a 100644 (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')
 
index 8639cf2e72cd7ae26549f7bb1ec206e81ca41bdb..bb9d3e88cfbee127ef4199c627754eaeb5da4d2e 100644 (file)
@@ -310,3 +310,8 @@ else:
     class cls310:
         def g():
             pass
+
+# line 314
+class ClassWithCodeObject:
+    import sys
+    code = sys._getframe(0).f_code
index 21d9f96c8c460e8c9b4f72044bccc04704d7bd33..dc46c0bc8ed35305959ef57283a82ba8983cd8bc 100644 (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)
 
diff --git a/Misc/NEWS.d/next/Library/2024-03-19-19-42-25.gh-issue-116987.ZVKUH1.rst b/Misc/NEWS.d/next/Library/2024-03-19-19-42-25.gh-issue-116987.ZVKUH1.rst
new file mode 100644 (file)
index 0000000..f2da956
--- /dev/null
@@ -0,0 +1 @@
+Fixed :func:`inspect.findsource` for class code objects.