[match-case]: `TypedDict` interaction with mapping pattern
Chưa có ai nhận issue này.
- Ngôn ngữ chính
- Python
- Star
- 1.8k
- Fork
- 302
- Merge trung bình
- 23 giờ
- Pull request đã merge (30 ngày)
- 8
Mô tả
It seems match-cases mapping pattern is predestined to work well with TypedDict, but currently the spec is silent regarding TypedDict subtyping with respect to match case: https://typing.python.org/en/latest/spec/typeddict.html#subtyping-with-mapping
At the time of writing, not a single type checker (tested with mypy=1.19.1, pyright=1.1.408, ty=0.0.17, pyrefly=0.53.0 and zuban=0.6.0) can solve the following tests[^1], suggesting that some standardization / typing spec guidance may be useful.
from typing import TypedDict, assert_type, assert_never
class D(TypedDict):
name: str
value: int
def test_match_key(x: D | int) -> None:
match x:
case {"name": _}:
# runtime equivalent to (isinstance(x, Mapping) and "name" in x)
assert_type(x, D)
case _:
assert_type(x, int)
def test_match_key_and_value(x: D | int) -> None:
match x:
case {"name": str()}:
# runtime equivalent to (isinstance(x, Mapping)
# and "name" in x and isinstance(x["name"], str))
assert_type(x, D)
case _:
assert_type(x, int)
def test_non_match(x: D | int) -> None:
match x:
case {"value": str()}:
# runtime equivalent to (isinstance(x, Mapping)
# and "value" in x and isinstance(x["value"], str))
assert_never(x)
case _:
assert_type(x, D | int)
[^1]: technically, it is possible to make a shared subclass of int and collections.abc.Mapping, so the assert_type in the case {...} are debatable, though the inference in the case _ branches should not be affected.
Hướng dẫn đóng góp
Chưa lập chỉ mục được hướng dẫn đóng góp cho kho mã nguồn này
Bắt đầu từ đâu
- Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
- Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
- Fork repository và làm thay đổi trên một nhánh.
- Mở pull request có tham chiếu số hiệu của issue.
Hướng nghiên cứu
Bắt đầu với phần TypedDict subtyping-with-mapping của typing specification và các quy tắc mapping pattern của PEP 634. Chạy ba ví dụ trên các type checker được liệt kê để so sánh hành vi hiện tại. Công việc được xem là hoàn tất khi đạt được sự thống nhất về narrowing dự kiến và ghi lại hướng dẫn chuẩn hóa, cùng với các trường hợp validation tương ứng.
Do mô hình lập chỉ mục viết ra từ nội dung của issue.
Đánh giá
- Công nghệ
- python
- Lĩnh vực
- devtools
- Loại issue
- Tính năng
- Độ khó
- 5/5
- Thời gian dự kiến
- Hơn một tuần
- Mức độ hoạt động
- Đình trệ
- Độ rõ ràng
- Khá rõ ràng
- Mức phù hợp với người mới
- 35/100