python / python/typing

Should operator `|` on `TypedDict` allow for creating intersection-like dicts?

Đang mở
#1,445 5 bình luận 0 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

topic: feature
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ả

I'm wondering how is the relation between the following PEPs:

  • PEP 584 which introduces operator | for dicts, but doesn't mention how it should behave for TypedDict.
  • PEP 589 which introduces TypedDict, but doesn't mention the operator |.

According to PEP 589, multiple inheritance can be used to create a combined (or "intersection like") dict, and operator | provides the corresponding behavior at runtime. Thus it would be nice if the type system could handle the combination properly (similar to how it is possible in TypeScript):

from typing import TypedDict

class HasFoo(TypedDict):
    foo: int
    
class HasBar(TypedDict):
    bar: int
    
class HasFooAndBar(HasFoo, HasBar):
    ...
    
def f(a: HasFoo, b: HasBar) -> HasFooAndBar:
    return a | b

From a runtime and type-checking perspective this code looks valid, but currently mypy does not accept it (playground):

main.py:15: error: Incompatible return value type (got "HasFoo", expected "HasFooAndBar")  [return-value]
main.py:15: error: Unsupported operand types for | ("HasFoo" and "HasBar")  [operator]

Pyright seems to have the same behavior.

Apparently operator | can only be used for two instances of the same typed dict, which as far as I can see has limited use cases, because using the operator | on two dicts that already have the same fields is kind of pointless (perhaps it mostly makes sense if the type used total=False).

Possible related discussions and issues I've found:

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

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. 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.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Hướng nghiên cứu

Bắt đầu bằng cách so sánh PEP 584 và PEP 589, sau đó tái hiện ví dụ TypedDict trong mypy playground được liên kết. Xem lại các cuộc thảo luận liên quan về typing, Pylance và Pyright để xác định liệu có sự đồng thuận về hành vi giống phép giao được đề xuất hay không. Công việc được xem là hoàn tất khi có ngữ nghĩa đã được thống nhất và một lộ trình được ghi lại để các type checker hỗ trợ hành vi này.

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
tooling
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
30/100

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.