python / python/cpython

`lazy import a.b as c` incorrectly binds to `a.b.b`

オープン
#157,614 コメント 6 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

3.15 3.16 interpreter-core release-blocker topic-lazy-imports type-bug
主要言語
Python
スター
77.2k
フォーク
35.9k
PR マージ指標
PR 指標を取得中

説明

Bug report

(Edited by @johnslavik)

To reproduce:

import importlib.metadata
import importlib.metadata as x
lazy import importlib.metadata as lazy_x

print("type(x):     ", type(x).__name__)  # reifies to importlib.metadata
print("type(lazy_x):", type(lazy_x).__name__)  # reifies to importlib.metadata.metadata

x.distributions()  # OK
lazy_x.distributions()  # AttributeError: 'function' object has no attribute 'distributions'

x is the importlib.metadata module, as expected. lazy_x is instead reified to importlib.metadata.metadata, the function.

The bug is in cached name resolution.

For lazy import a.b as c, the issue reproduces when:

  1. a.b is already in sys.modules.
  2. a.b has an attribute named b.
  3. c is reified.
Possible root cause

The problem may be in _PyEval_LazyImportFrom: [Python/ceval.c:3305-3361](https://github.com/python/cpython/blob/cf312cfa64dcaa1700531ec8bc76d56ddd65fb15/Python/ceval.c#L3305-L3361) (3.15 at cf312cfa64dcaa1700531ec8bc76d56ddd65fb15, v3.15.0rc2-22-gcf312cf).

The sys.modules fast path at lines 3313-3331 runs before the base-module computation at 3333-3360 and looks up name directly in d->lz_from.

In the IMPORT_FROM chain generated for import a.b.c as x, however, d->lz_from does not appear to be the module the attribute should be taken from: on the first step it is the full dotted name, and on later steps it is one component short of the base.

CPython versions tested on:

3.15

Operating systems tested on:

Linux

Linked PRs
  • gh-157626

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

まずリンクされている PR gh-157626 を確認し、次に Python/ceval.c の 3305~3361 行付近にある _PyEval_LazyImportFrom を調べます。sys.modules の fast path とキャッシュされた名前の解決に重点を置いてください。importlib.metadata の例で動作を再現します。lazy import a.b as c によって c が a.b.b ではなく a.b に束縛され、回帰が関連するテストでカバーされれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
compilers
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
明確に書かれている
初心者へのやさしさ
35/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。