Skip to content

Commit 0e707b4

Browse files
bpo-6700: Fix inspect.getsourcelines for module level frames/tracebacks (GH-8864)
(cherry picked from commit 91cb298) Co-authored-by: Vladimir Matveev <[email protected]>
1 parent 902f161 commit 0e707b4

File tree

4 files changed

+26
-3
lines changed

4 files changed

+26
-3
lines changed

Lib/inspect.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -954,7 +954,12 @@ def getsourcelines(object):
954954
object = unwrap(object)
955955
lines, lnum = findsource(object)
956956

957-
if ismodule(object):
957+
if istraceback(object):
958+
object = object.tb_frame
959+
960+
# for module or frame that corresponds to module, return all source lines
961+
if (ismodule(object) or
962+
(isframe(object) and object.f_code.co_name == "<module>")):
958963
return lines, 0
959964
else:
960965
return getblock(lines[lnum:]), lnum + 1

Lib/test/inspect_fodder.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,3 +74,9 @@ def contradiction(self):
7474

7575
async def lobbest(grenade):
7676
pass
77+
78+
currentframe = inspect.currentframe()
79+
try:
80+
raise Exception()
81+
except:
82+
tb = sys.exc_info()[2]

Lib/test/test_inspect.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -322,7 +322,7 @@ def setUp(self):
322322

323323
def sourcerange(self, top, bottom):
324324
lines = self.source.split("\n")
325-
return "\n".join(lines[top-1:bottom]) + "\n"
325+
return "\n".join(lines[top-1:bottom]) + ("\n" if bottom else "")
326326

327327
def assertSourceEqual(self, obj, top, bottom):
328328
self.assertEqual(inspect.getsource(obj),
@@ -497,6 +497,16 @@ def monkey(filename, module_globals=None):
497497
def test_getsource_on_code_object(self):
498498
self.assertSourceEqual(mod.eggs.__code__, 12, 18)
499499

500+
class TestGettingSourceOfToplevelFrames(GetSourceBase):
501+
fodderModule = mod
502+
503+
def test_range_toplevel_frame(self):
504+
self.maxDiff = None
505+
self.assertSourceEqual(mod.currentframe, 1, None)
506+
507+
def test_range_traceback_toplevel_frame(self):
508+
self.assertSourceEqual(mod.tb, 1, None)
509+
500510
class TestDecorators(GetSourceBase):
501511
fodderModule = mod2
502512

@@ -3747,7 +3757,7 @@ def test_main():
37473757
TestBoundArguments, TestSignaturePrivateHelpers,
37483758
TestSignatureDefinitions,
37493759
TestGetClosureVars, TestUnwrap, TestMain, TestReload,
3750-
TestGetCoroutineState
3760+
TestGetCoroutineState, TestGettingSourceOfToplevelFrames
37513761
)
37523762

37533763
if __name__ == "__main__":
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix inspect.getsourcelines for module level frames/tracebacks.
2+
Patch by Vladimir Matveev.

0 commit comments

Comments
 (0)