Skip to content

Commit 91cb298

Browse files
vladimataleinat
authored andcommitted
bpo-6700: Fix inspect.getsourcelines for module level frames/tracebacks (GH-8864)
1 parent 075b3c3 commit 91cb298

File tree

4 files changed

+26
-3
lines changed

4 files changed

+26
-3
lines changed

Lib/inspect.py

+6-1
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

+6
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

+12-2
Original file line numberDiff line numberDiff line change
@@ -344,7 +344,7 @@ def setUp(self):
344344

345345
def sourcerange(self, top, bottom):
346346
lines = self.source.split("\n")
347-
return "\n".join(lines[top-1:bottom]) + "\n"
347+
return "\n".join(lines[top-1:bottom]) + ("\n" if bottom else "")
348348

349349
def assertSourceEqual(self, obj, top, bottom):
350350
self.assertEqual(inspect.getsource(obj),
@@ -527,6 +527,16 @@ def monkey(filename, module_globals=None):
527527
def test_getsource_on_code_object(self):
528528
self.assertSourceEqual(mod.eggs.__code__, 12, 18)
529529

530+
class TestGettingSourceOfToplevelFrames(GetSourceBase):
531+
fodderModule = mod
532+
533+
def test_range_toplevel_frame(self):
534+
self.maxDiff = None
535+
self.assertSourceEqual(mod.currentframe, 1, None)
536+
537+
def test_range_traceback_toplevel_frame(self):
538+
self.assertSourceEqual(mod.tb, 1, None)
539+
530540
class TestDecorators(GetSourceBase):
531541
fodderModule = mod2
532542

@@ -3870,7 +3880,7 @@ def test_main():
38703880
TestBoundArguments, TestSignaturePrivateHelpers,
38713881
TestSignatureDefinitions, TestIsDataDescriptor,
38723882
TestGetClosureVars, TestUnwrap, TestMain, TestReload,
3873-
TestGetCoroutineState
3883+
TestGetCoroutineState, TestGettingSourceOfToplevelFrames
38743884
)
38753885

38763886
if __name__ == "__main__":
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)