Broken circular import between `threading` and `_threading_local`
還沒有人認領這個 Issue。
- 主要語言
- Python
- 星號
- 77.2k
- 分支
- 35.9k
- PR 合併指標
- PR 指標待擷取
描述
Bug report
Bug description:
The threading module defines local as follows:
But _threading_local also uses threading as follows:
This was fine at first, since threading never used thread-local data (the import was near the end). However, this changed in gh-114424:
The _threading_local.local object depends on threading.current_thread(), and this dependency occurs when the object is created:
https://github.com/python/cpython/blob/ee521e8ac19ad012ebc4e1b3e71b369988a9b9f8/Lib/_threading_local.py#L93-L96
https://github.com/python/cpython/blob/ee521e8ac19ad012ebc4e1b3e71b369988a9b9f8/Lib/_threading_local.py#L42-L46
The object is created (and local is imported) before current_thread() is defined. As a result, there is the broken circular import, which can be reproduced as follows:
>>> import _thread
>>> del _thread._local
>>> import threading
Traceback (most recent call last):
File "/home/user/.local/share/mise/installs/python/3.14.7/lib/python3.14/threading.py", line 67, in <module>
from _thread import _local as local
ImportError: cannot import name '_local' from '_thread' (unknown location)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<python-input-2>", line 1, in <module>
import threading
File "/home/user/.local/share/mise/installs/python/3.14.7/lib/python3.14/threading.py", line 69, in <module>
from _threading_local import local
File "/home/user/.local/share/mise/installs/python/3.14.7/lib/python3.14/_threading_local.py", line 120, in <module>
from threading import current_thread, RLock
ImportError: cannot import name 'current_thread' from partially initialized module 'threading' (most likely due to a circular import) (/home/user/.local/share/mise/installs/python/3.14.7/lib/python3.14/threading.py)
Since the issue has not been reported before, this raises a legitimate question: is the fallback still relevant?
Related: #141460.
CPython versions tested on:
3.13, 3.14
Operating systems tested on:
Linux
Linked PRs
- gh-157042
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
閱讀所引用的匯入和物件建立位置中的 Lib/threading.py 和 Lib/_threading_local.py。在匯入 threading 前刪除 _thread._local,以重現此故障,然後檢視相關 issue #141460 和連結的 PR gh-157042。循環匯入獲得解決,且示範的 fallback 行為由回歸測試涵蓋,即表示完成。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- python
- 領域
- backend
- Issue 類型
- 缺陷
- 難度
- 4/5
- 預估耗時
- 3-5 天
- 活躍度
- 停滯
- 描述清晰度
- 基本清楚
- 新手友好度
- 30/100