Exhaustiveness checking fails on non-trivial use of pattern matching
還沒有人認領這個 Issue。
評估
研究方向
先使用 assert_never()、match-case、Sequence 模式,以及 issue 中所示的包裝 Enum 屬性重現這兩個範例。追蹤 mypy 對這些情況的窮舉性與 narrowing 行為;完成的標準是:受支援的非平凡 match 被識別為窮舉,而不會出現回報的型別錯誤,並為這些範例提供覆蓋。
由索引模型根據 Issue 內容生成。
描述
Code using assert_never() to ensure exhaustive use of match-case yields a type error on many non-trivial cases.
mypy can only verify exhaustiveness when matching directly against a Union type or Enum value.
Though, proving the exhaustiveness of non-trivial matches may be beyond mypy domain. Here are a couple of examples for the sake of argument:
Matching on both [] and [x, *xs] on Sequence will not narrow the type
from collections.abc import Sequence
from typing import assert_never
def my_sum(s: Sequence[float]) -> float:
match s:
case []:
return 0
case [num, *rest]:
return num + my_sum(rest)
case _ as u:
# error: Argument 1 to "assert_never" has incompatible type "Sequence[float]"; expected "NoReturn"
return assert_never(u)
Matching against all Enum values that a single-member wrapper class may contain
import dataclasses, enum
from typing import assert_never, final
class E(enum.Enum):
A = enum.auto()
B = enum.auto()
@final
@dataclasses.dataclass(frozen=True)
class Foo:
x: E
def match_enum_attribute(f: Foo) -> None:
match f:
case Foo(E.A):
pass
case Foo(E.B):
pass
case _ as r:
# error: Argument 1 to "assert_never" has incompatible type "Foo"; expected "NoReturn" [arg-type]
assert_never(r)
- 主要語言
- Python
- 星號
- 20.6k
- 分支
- 3.3k
- 平均合併
- 1 天 18 小時
- 30 天內合併 PR
- 54
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
python/mypy 的其他 Issue
-
bug
難度 2/5 1-3 小時 新手友好度 75/100
-
bug
難度 2/5 1-3 小時 新手友好度 78/100
-
bug
難度 2/5 1-3 小時 新手友好度 76/100
-
documentation
難度 2/5 1-3 小時 新手友好度 72/100
-
bug topic-configuration topic-error-reporting
難度 2/5 1-3 小時 新手友好度 68/100
相似的 Issue
-
area/auth bug comp/agent P3 platform/discord type/security
難度 2/5 1-3 小時 新手友好度 88/100
NousResearch/hermes-agent#117848 ·
-
難度 2/5 1-3 小時 新手友好度 74/100
bancolombia/sentinel#23 ·
-
test md 未關閉CI
難度 2/5 1-3 小時 新手友好度 74/100
-
integration:quickjs org:external priority:backlog topic:code-interpreter topic:middleware type:feature
難度 2/5 1-3 小時 新手友好度 74/100
langchain-ai/deepagents#6450 ·
-
bug client
難度 2/5 1-3 小時 新手友好度 88/100