importlib.resources.files() doesn't work correctly when importlib library is compiled
還沒有人認領這個 Issue。
- 主要語言
- Python
- 星號
- 77.2k
- 分支
- 35.9k
- PR 合併指標
- PR 指標待擷取
描述
Bug report
Bug description:
If importlib library is compiled (in particular _common.py), then any package, that uses bare files() to get its resources, breaks, because _infer_caller returns wrong frame (as mentioned in https://github.com/python/cpython/pull/123037#issuecomment-2294431430, __file__ in https://github.com/python/cpython/blob/35d8ac7cd7ed6cd3d84af721dce970da59bd5f68/Lib/importlib/resources/_common.py#L96 is not valid)
Reproducer:
import importlib
import os
import pathlib
import py_compile
import shutil
import sys
import tempfile
import textwrap
def compile(tempdir):
target_dir = pathlib.Path(tempdir) / 'cimportlib'
souce_dir = pathlib.Path(importlib.__file__).parent
shutil.copytree(souce_dir, target_dir, ignore=lambda *_: ['__pycache__'])
for dirpath, _, filenames in os.walk(target_dir):
for filename in filenames:
if filename != "_common.py":
continue
source_path = pathlib.Path(dirpath) / filename
cfile = source_path.with_suffix('.pyc')
py_compile.compile(source_path, cfile)
pathlib.Path.unlink(source_path)
def create_package(tempdir):
package_dir = pathlib.Path(tempdir) / 'somepkg'
package_dir.mkdir()
contents = {
"__init__.py": textwrap.dedent(
"""
import cimportlib.resources as res
val = res.files().joinpath('resource.txt').read_text(encoding='utf-8')
"""
),
"resource.txt": "data",
}
for file, content in contents.items():
path = pathlib.Path(package_dir) / file
path.write_text(content)
def main():
with tempfile.TemporaryDirectory() as tempdir:
compile(tempdir)
create_package(tempdir)
sys.path.insert(0, str(tempdir))
print(importlib.import_module('somepkg').val)
if __name__ == "__main__":
raise SystemExit(main())
Expectation:
data
Actual outcome:
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/tmpngnuw441/cimportlib/resources/resource.txt'
It may be important for frozen python applications, as they don't include source code
CPython versions tested on:
3.12, CPython main branch
Operating systems tested on:
Linux, Windows
Linked PRs
- gh-123102
- gh-124021
- gh-124024
- gh-124131
- gh-128581
- gh-128600
- gh-137914
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
從 Lib/importlib/resources/_common.py 開始,特別查看 _infer_caller 和參照的那一行,然後使用已編譯的 _common.py,透過提供的指令碼重現失敗。將預期的資料輸出與 FileNotFoundError 進行比較;當重現程式能在已編譯的 importlib 中運作,且正常的資源載入沒有回歸時,即表示完成。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- python
- 領域
- backend
- Issue 類型
- 缺陷
- 難度
- 4/5
- 預估耗時
- 3-5 天
- 活躍度
- 停滯
- 描述清晰度
- 基本清楚
- 新手友好度
- 25/100