This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: If module starts with comment or empty line then frame.f_code.co_firstlineno is inconsistent with inspect.findsource
Type: behavior Stage: resolved
Components: Interpreter Core Versions: Python 3.6, Python 3.5
process
Status: closed Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: Aivar.Annamaa, emilyemorehouse, louielu, yselivanov
Priority: normal Keywords:

Created on 2016-09-13 08:38 by Aivar.Annamaa, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (3)
msg276211 - (view) Author: Aivar Annamaa (Aivar.Annamaa) * Date: 2016-09-13 08:38
Following program shows that frame.f_code.co_firstlineno ignores first line if it is a comment (or empty line), but inspect.getsource(frame.f_code) returns also the first line:

# first line
import inspect
frame = inspect.currentframe()
print(frame.f_code.co_firstlineno)
print(inspect.findsource(frame.f_code))
msg288425 - (view) Author: Louie Lu (louielu) * Date: 2017-02-23 08:44
Sorry, but I can't reproduce at 3.7, 3.5, or 2.7.
the result shows me that inspect does respect comment line.

➜  cpython git:(350) ✗ ./python /tmp/main.py
2
(['# First line\n', 'import inspect\n', 'frame = inspect.currentframe()\n', 'print(frame.f_code.co_firstlineno)\n', 'print(inspect.findsource(frame.f_code))\n'], 0)

➜  /tmp python2 main.py
2
(['# First line\n', 'import inspect\n', 'frame = inspect.currentframe()\n', 'print(frame.f_code.co_firstlineno)\n', 'print(inspect.findsource(frame.f_code))\n'], 0)
msg288432 - (view) Author: Aivar Annamaa (Aivar.Annamaa) * Date: 2017-02-23 09:38
Looks like I misinderstood inspect.findsource. I thought it is supposed to give only the code for argument object (eg. only def code when given a function), but looks like it is giving the whole file.

Unfortunately inspect.findsource is not documented in https://docs.python.org/3/library/inspect.html and inspect.getsource can't be used as replacement, because it doesn't work with modules.
History
Date User Action Args
2022-04-11 14:58:36adminsetgithub: 72308
2017-02-23 09:38:54Aivar.Annamaasetstatus: open -> closed

stage: resolved
messages: + msg288432
versions: + Python 3.6
2017-02-23 08:44:20louielusetnosy: + louielu
messages: + msg288425
2017-02-21 16:36:50emilyemorehousesetnosy: + emilyemorehouse
2016-09-13 09:46:33SilentGhostsetnosy: + yselivanov
2016-09-13 08:39:03Aivar.Annamaasettype: behavior
components: + Interpreter Core
versions: + Python 3.5
2016-09-13 08:38:34Aivar.Annamaacreate