Hacktoberfest 2026:维护者为十月标记出来的 issue,仍然开放、适合新手。 浏览 Hacktoberfest issue

Inferred attribute type feeds back as call context, rejecting its own defining assignment

未关闭
#21,809 1 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

评估

难度
4/5
预计耗时
3-5 天
新手友好度
48/100
Issue 类型
缺陷
描述清晰度
基本清楚
活跃度
冷清
技术栈
python
领域
compilers

调研方向

从 issue 中的复现用例开始,跟踪针对向未声明的 self 属性赋值的延迟异步重新检查。将该路径与通过的局部属性和带注解属性用例进行比较,重点关注推断出的返回上下文如何传递到泛型参数推断。完成标准是复现用例能够在将 K 推断为 str 的情况下通过,并且回归测试覆盖此行为。

由索引模型根据 Issue 内容生成。

描述

bug

Bug Report

Assigning a generic call returning K | None to a previously undeclared
self. attribute spuriously fails [arg-type] on that same assignment. The
attribute's inferred type (str | None) apparently comes back as call context
on a later pass, solving K = str | None; the invariant Mapping key then
rejects dict[str, str].

The same expression passes with no context, an annotated local, an annotated
attribute, or a reassigned local (whose second assignment is likewise checked
against its own inferred str | None) — the optional-stripping special case
seems skipped on the inferred-attribute path alone. A sync version (no
async/await) also passes, pointing at the deferred re-check await
triggers.

To Reproduce

from collections.abc import Mapping


async def select_one[K](options: Mapping[K, str]) -> K | None: ...


class ViaInferredAttr:
    async def m(self) -> None:
        cases = {"a": "x"}
        self._done = await select_one(cases)  # error (spurious)


async def via_local() -> None:
    cases = {"a": "x"}
    done = await select_one(cases)  # ok
    done = await select_one(cases)  # ok (context = inferred str | None)
    done2: str | None = await select_one(cases)  # ok


class ViaAnnotatedAttr:
    _done: str | None

    async def m(self) -> None:
        cases = {"a": "x"}
        self._done = await select_one(cases)  # ok

Expected Behavior

All call sites typecheck, with K = str.

Actual Behavior

repro.py:10: error: Argument 1 to "select_one" has incompatible type "dict[str, str]"; expected "Mapping[str | None, str]"  [arg-type]

The str | None key shows the return's | None leaked into K.

Your Environment

  • mypy 1.20.2 (compiled), no flags
  • Python 3.13

Related: #5874 (over-eager outer context with unions), #19304 (assignment target
changes results). New here: the context is self-inferred — no annotation exists
anywhere — and explicit spellings of the same type behave differently.

主要语言
Python
星标
20.6k
派生
3.3k
平均合并
1 天 12 小时
30 天内合并 PR
58

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

python/mypy 的其他 Issue

查看 python/mypy 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。