Skip to content

GH-103319: Fix inspect.getsourcelines() to return 1-based line numbers #103226

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion Lib/inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -1260,7 +1260,7 @@ def getsourcelines(object):
# 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
return lines, 1
else:
return getblock(lines[lnum:]), lnum + 1

Expand Down
11 changes: 11 additions & 0 deletions Lib/test/test_inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -654,6 +654,17 @@ def test_getsourcefile(self):
finally:
del linecache.cache[co.co_filename]

def test_getsourcelines(self):
# Check source lines and starting line number for a module
mod_lines, mod_lineno = inspect.getsourcelines(mod)
self.assertEqual(len(mod_lines), 115)
self.assertEqual(mod_lineno, 1)

# Check source lines and starting line number for a function
spam_lines, spam_lineno = inspect.getsourcelines(mod.spam)
self.assertEqual(len(spam_lines), 2)
self.assertEqual(spam_lineno, 8)

def test_getfile(self):
self.assertEqual(inspect.getfile(mod.StupidGit), mod.__file__)

Expand Down
25 changes: 25 additions & 0 deletions Lib/test/test_pdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -1675,6 +1675,31 @@ def test_pdb_issue_gh_101673():
(Pdb) continue
"""

def test_pdb_issue_gh_103225():
"""See GH-103225

Make sure longlist uses 1-based line numbers in frames that correspond to a module

>>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
... 'longlist',
... 'continue'
... ]):
... a = 1
... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
... b = 2
> <doctest test.test_pdb.test_pdb_issue_gh_103225[0]>(7)<module>()
-> b = 2
(Pdb) longlist
1 with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE
2 'longlist',
3 'continue'
4 ]):
5 a = 1
6 import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()
7 -> b = 2
(Pdb) continue
"""


@support.requires_subprocess()
class PdbTestCase(unittest.TestCase):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix :func:`inspect.getsourcelines` function to return 1-based line numbers for modules and frames that correspond to modules.