Skip to content

Commit 088a15c

Browse files
authored
bpo-43933: Show frame.f_lineno as None, rather than -1, if there is no line number. (GH-25717)
1 parent 2fd928c commit 088a15c

File tree

3 files changed

+20
-2
lines changed

3 files changed

+20
-2
lines changed

Lib/test/test_exceptions.py

+10-1
Original file line numberDiff line numberDiff line change
@@ -2081,7 +2081,10 @@ def lineno_after_raise(self, f, line):
20812081
while t.tb_next:
20822082
t = t.tb_next
20832083
frame = t.tb_frame
2084-
self.assertEqual(frame.f_lineno-frame.f_code.co_firstlineno, line)
2084+
if line is None:
2085+
self.assertEqual(frame.f_lineno, line)
2086+
else:
2087+
self.assertEqual(frame.f_lineno-frame.f_code.co_firstlineno, line)
20852088

20862089
def test_lineno_after_raise_simple(self):
20872090
def simple():
@@ -2153,6 +2156,12 @@ def after_with():
21532156
pass
21542157
self.lineno_after_raise(after_with, 2)
21552158

2159+
def test_missing_lineno_shows_as_none(self):
2160+
def f():
2161+
1/0
2162+
self.lineno_after_raise(f, 1)
2163+
f.__code__ = f.__code__.replace(co_linetable=b'\x04\x80\xff\x80')
2164+
self.lineno_after_raise(f, None)
21562165

21572166
if __name__ == '__main__':
21582167
unittest.main()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
If the current position in a frame has no line number then set the f_lineno
2+
attribute to None, instead of -1, to conform to PEP 626. This should not
3+
normally be possible, but might occur in some unusual circumstances.

Objects/frameobject.c

+7-1
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,13 @@ PyFrame_GetLineNumber(PyFrameObject *f)
5353
static PyObject *
5454
frame_getlineno(PyFrameObject *f, void *closure)
5555
{
56-
return PyLong_FromLong(PyFrame_GetLineNumber(f));
56+
int lineno = PyFrame_GetLineNumber(f);
57+
if (lineno < 0) {
58+
Py_RETURN_NONE;
59+
}
60+
else {
61+
return PyLong_FromLong(lineno);
62+
}
5763
}
5864

5965
static PyObject *

0 commit comments

Comments
 (0)