TracebackException.lineno changes from str to int after format() when a keyword typo suggestion is found

未關閉 適合新手
#162,296 1 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

維護者通常 1 天內回覆

@Sudhakar7J 已經在處理了。

開始於 2026年11月20日。

  • #162328 來自 @Sudhakar7J —— 未關閉

評估

難度
2/5
預估耗時
1-3 小時
新手友好度
67/100
Issue 類型
缺陷
描述清晰度
基本清楚
活躍度
活躍
技術堆疊
python
領域
backend

研究方向

從 TracebackException._find_keyword_typos() 著手,檢查它如何指定 lineno 和 end_lineno;issue 指出,建構子的字串轉換是預期行為。閱讀有關關鍵字拼寫錯誤建議的 traceback 測試,並補上格式化前後屬性型別的測試涵蓋。格式化保留文件所述或已確立的型別,且迴歸測試通過,即表示完成。

由索引模型根據 Issue 內容生成。

描述

stdlib type-bug
Bug report

For a SyntaxError, TracebackException stores lineno and end_lineno as strings. When the keyword typo suggestion ("Did you mean 'while'?") triggers during formatting, both attributes are replaced with ints.

import sys
import traceback

print(sys.version)

try:
    compile("whille True:\n    pass\n", "example.py", "exec")
except SyntaxError as exc:
    te = traceback.TracebackException.from_exception(exc)

print("before format():", repr(te.lineno), repr(te.end_lineno))
"".join(te.format())
print("after format(): ", repr(te.lineno), repr(te.end_lineno))

On main:

3.16.0a2+dev (remotes/origin/HEAD:d456158, Nov 19 2026, 22:08:35) [GCC 13.3.0]
before format(): '1' '1'
after format():  1 1

On 3.14:

3.14.6 (main, Jul 18 2026, 17:01:31) [Clang 22.1.3 ]
before format(): '1' '1'
after format():  1 1

On 3.13.18 both stay '1', since there are no keyword suggestions there.

The constructor does self.lineno = str(lno), but TracebackException._find_keyword_typos() later assigns self.lineno = start[0] and self.end_lineno = end[0], which are ints from the tokenizer.

The printed traceback is fine, so most people won't notice this. It only shows up if your code reads the attributes directly. For example, te.lineno == '1' is True before calling format() and False after.

It also affects equality: two TracebackException objects created from the same exception compare equal, but stop being equal after you format one of them.

I think the two assignments should be wrapped in str() to match the constructor. I'm happy to send a PR with a test if that's the right direction. The docs don't currently state the type of these attributes, so that could be clarified at the same time.

CPython versions tested on:

CPython main branch

Operating systems tested on:

macOS

主要語言
Python
星號
78.4k
分支
36.6k
平均合併
23 小時 34 分鐘
30 天內合併 PR
610

環境準備

在 Codespaces 中開啟

在瀏覽器裡用你自己的 GitHub 帳號啟動這個專案的開發容器。

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

python/cpython 的其他 Issue

查看 python/cpython 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。