bpo-6700: Fix inspect.getsourcelines for module level frames/tracebacks (GH-8864)
(cherry picked from commit 91cb298f811961277fd4cc4a32211899d48bedcb)
Co-authored-by: Vladimir Matveev <v2matveev@outlook.com>
diff --git a/Lib/inspect.py b/Lib/inspect.py
index 288bfbb..4482b8e 100644
--- a/Lib/inspect.py
+++ b/Lib/inspect.py
@@ -954,7 +954,12 @@
object = unwrap(object)
lines, lnum = findsource(object)
- if ismodule(object):
+ if istraceback(object):
+ object = object.tb_frame
+
+ # for module or frame that corresponds to module, return all source lines
+ if (ismodule(object) or
+ (isframe(object) and object.f_code.co_name == "<module>")):
return lines, 0
else:
return getblock(lines[lnum:]), lnum + 1
diff --git a/Lib/test/inspect_fodder.py b/Lib/test/inspect_fodder.py
index 711bada..ff3f0e4 100644
--- a/Lib/test/inspect_fodder.py
+++ b/Lib/test/inspect_fodder.py
@@ -74,3 +74,9 @@
async def lobbest(grenade):
pass
+
+currentframe = inspect.currentframe()
+try:
+ raise Exception()
+except:
+ tb = sys.exc_info()[2]
diff --git a/Lib/test/test_inspect.py b/Lib/test/test_inspect.py
index 8b70161..ee5a2d4 100644
--- a/Lib/test/test_inspect.py
+++ b/Lib/test/test_inspect.py
@@ -344,7 +344,7 @@
def sourcerange(self, top, bottom):
lines = self.source.split("\n")
- return "\n".join(lines[top-1:bottom]) + "\n"
+ return "\n".join(lines[top-1:bottom]) + ("\n" if bottom else "")
def assertSourceEqual(self, obj, top, bottom):
self.assertEqual(inspect.getsource(obj),
@@ -527,6 +527,16 @@
def test_getsource_on_code_object(self):
self.assertSourceEqual(mod.eggs.__code__, 12, 18)
+class TestGettingSourceOfToplevelFrames(GetSourceBase):
+ fodderModule = mod
+
+ def test_range_toplevel_frame(self):
+ self.maxDiff = None
+ self.assertSourceEqual(mod.currentframe, 1, None)
+
+ def test_range_traceback_toplevel_frame(self):
+ self.assertSourceEqual(mod.tb, 1, None)
+
class TestDecorators(GetSourceBase):
fodderModule = mod2
@@ -3815,7 +3825,7 @@
TestBoundArguments, TestSignaturePrivateHelpers,
TestSignatureDefinitions,
TestGetClosureVars, TestUnwrap, TestMain, TestReload,
- TestGetCoroutineState
+ TestGetCoroutineState, TestGettingSourceOfToplevelFrames
)
if __name__ == "__main__":