Sentinel and enum type merge issues with generic

未關閉
#22,334 2 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

維護者通常 1 天內回覆

@edgarrmondragon 已經在處理了。

開始於 2026年11月2日。

  • #22351 來自 @edgarrmondragon —— 未關閉

評估

難度
4/5
預估耗時
3-5 天
新手友好度
49/100
Issue 類型
缺陷
描述清晰度
描述清楚
活躍度
活躍
技術堆疊
python
領域
compilers

研究方向

Start by running the supplied examples through mypy and compare direct assignment with assigning the result to a temporary. Check both the sentinel and enum cases against the working int example. Done means the direct assignments are accepted and the revealed types match the expected results.

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

描述

bug
from typing_extensions import sentinel

Undefined = sentinel("Undefined")

def none_if_undefined[_T](value: _T | Undefined) -> _T | None:
    return None if value is Undefined else value

def func() -> None:
    device_id: str | Undefined | None = Undefined
    device_id = none_if_undefined(device_id)  # <-- error
    reveal_type(device_id)
test.py:10: error: Argument 1 to "none_if_undefined" has incompatible type "str | Undefined | None"; expected "str | Undefined"  [arg-type]
test.py:11: note: Revealed type is "str | Undefined | None"

However, assigning the result from none_if_undefined to a temporary variable first works as expected.

def func() -> None:
    device_id: str | Undefined | None = Undefined
    x = none_if_undefined(device_id)
    reveal_type(x)
    device_id = x
    reveal_type(device_id)
test.py:11: note: Revealed type is "str | None"
test.py:13: note: Revealed type is "str | None"

--
A similar issues exists for enums

from enum import Enum
from typing import Literal

class E(Enum):
    SPECIAL = 1

def none_if_special[_T](value: _T | Literal[E.SPECIAL]) -> _T | None:
    return None if value is E.SPECIAL else value

def func() -> None:
    device_id: str | Literal[E.SPECIAL] | None = E.SPECIAL
    device_id = none_if_special(device_id)  # <-- error
    reveal_type(device_id)
test.py:12: error: Argument 1 to "none_if_special" has incompatible type "str | Literal[E.SPECIAL] | None"; expected "str | Literal[E.SPECIAL]"  [arg-type]
test.py:13: note: Revealed type is "str | Literal[test7.E.SPECIAL] | None"

--
For completeness the related example with just int - that works fine -- no errors.

def none_if_int[_T](value: _T | int) -> _T | None:
    return None if isinstance(value, int) else value

def func() -> None:
    device_id: str | int | None = 42
    device_id = none_if_int(device_id)
    reveal_type(device_id)
主要語言
Python
星號
20.7k
分支
3.4k
平均合併
1 天 15 小時
30 天內合併 PR
114

環境準備

從這裡開始

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

python/mypy 的其他 Issue

查看 python/mypy 的全部 Issue

相似的 Issue

更多 Python Issue

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

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