Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion Lib/inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -954,7 +954,12 @@ def getsourcelines(object):
object = unwrap(object)
lines, lnum = findsource(object)

if ismodule(object):
if istraceback(object):
object = object.tb_frame

# for module or frame that correspond to module return all source lines

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"... correspond to a module return ..." -> "... corresponds to a module, return ..."

if (ismodule(object) or
(isframe(object) and object.f_code.co_name == "<module>")):
return lines, 0
else:
return getblock(lines[lnum:]), lnum + 1
Expand Down
6 changes: 6 additions & 0 deletions Lib/test/inspect_fodder.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,9 @@ def contradiction(self):

async def lobbest(grenade):
pass

currentframe = inspect.currentframe()
try:
raise Exception()
except:
tb = sys.exc_info()[2]
11 changes: 10 additions & 1 deletion Lib/test/test_inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,15 @@ def monkey(filename, module_globals=None):
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.assertSourceEqual(mod.currentframe, 1, 82)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The 82 here (and below) is fragile, it would need to be updated after almost any minor change to the "fodder module". I suggest using None, which is equivalent to an open-ended slice, e.g. lines[1:].


def test_range_traceback_toplevel_frame(self):
self.assertSourceEqual(mod.tb, 1, 82)

class TestDecorators(GetSourceBase):
fodderModule = mod2

Expand Down Expand Up @@ -3870,7 +3879,7 @@ def test_main():
TestBoundArguments, TestSignaturePrivateHelpers,
TestSignatureDefinitions, TestIsDataDescriptor,
TestGetClosureVars, TestUnwrap, TestMain, TestReload,
TestGetCoroutineState
TestGetCoroutineState, TestGettingSourceOfToplevelFrames
)

if __name__ == "__main__":
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix inspect.getsourcelines for module level frames/tracebacks