https://github.com/python/cpython/commit/d16c9d1278164f04778861814ebc87ed087511fc
commit: d16c9d1278164f04778861814ebc87ed087511fc
branch: main
author: Tian Gao <[email protected]>
committer: serhiy-storchaka <[email protected]>
date: 2024-03-21T10:30:10Z
summary:
gh-116987: Support class code objects in inspect.findsource() (GH-117025)
files:
A Misc/NEWS.d/next/Library/2024-03-19-19-42-25.gh-issue-116987.ZVKUH1.rst
M Lib/inspect.py
M Lib/test/test_inspect/inspect_fodder2.py
M Lib/test/test_inspect/test_inspect.py
diff --git a/Lib/inspect.py b/Lib/inspect.py
index 7336cea0dc3fdc..422c09a92ad141 100644
--- a/Lib/inspect.py
+++ b/Lib/inspect.py
@@ -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')
diff --git a/Lib/test/test_inspect/inspect_fodder2.py
b/Lib/test/test_inspect/inspect_fodder2.py
index 8639cf2e72cd7a..bb9d3e88cfbee1 100644
--- a/Lib/test/test_inspect/inspect_fodder2.py
+++ b/Lib/test/test_inspect/inspect_fodder2.py
@@ -310,3 +310,8 @@ def f():
class cls310:
def g():
pass
+
+# line 314
+class ClassWithCodeObject:
+ import sys
+ code = sys._getframe(0).f_code
diff --git a/Lib/test/test_inspect/test_inspect.py
b/Lib/test/test_inspect/test_inspect.py
index 21d9f96c8c460e..dc46c0bc8ed353 100644
--- a/Lib/test/test_inspect/test_inspect.py
+++ b/Lib/test/test_inspect/test_inspect.py
@@ -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)
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
index 00000000000000..f2da956f66c86b
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2024-03-19-19-42-25.gh-issue-116987.ZVKUH1.rst
@@ -0,0 +1 @@
+Fixed :func:`inspect.findsource` for class code objects.
_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-checkins.python.org/
Member address: [email protected]