python / python/typing

Allow TypedDict.__required_keys__/__optional_keys__ to be used as Literal[...]

Đang mở
#1,394 6 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ả

TypedDict instances work very well for NoSQL databases, like Mongo DB, but for any extended functionality a class is required, and marrying the two requires a few error-prone steps described here.

Consider a Mongo DB database document described with this structure, which works out well to the most part when being supplied into pymongo methods (with the exception of mypy failing to realize that it's TypedDict is a mutable mapping).

class X(TypedDict):
    i: int
    s: str
    f: NotRequired[float]

Compared to Mapping, using a typed dictionary allows one to catch field references and value type mismatches quite quickly.

For more advanced functionality for this entity, however, a class may be maintained, like below. I will omit getters, etc, and just show relevant methods to set required and optional fields.

class Y:
    def __init__(self, x: X) -> None:
        self._storage = x

    def set_required(self, key: Literal["i", "s"], value: Any) -> None:
        self._storage[key] = value

    def set_optional(self, key: Literal["f"], value: Any) -> None:
        if value is None:
            del self._storage[key]
        else:
            self._storage[key] = value

Herein lies the problem - I cannot use X.__required_keys__ to drive field references in the underlying storage because it's not a literal and the fact that it's frozenset doesn't help here, so I have to maintain copies of field names separately.

If X.__required_keys__ and X.__optional_keys__ would operate similarly to how constexpr behaves in C++ and would propagate literal keys they are created with to where they are used, like those methods above, it would make it very straightforward to integrate typed dictionaries with classes and use the former as storage with a well-defined schema that can be referenced in class methods to enforce proper field references.

I will also note that @dataclass is not good for this functionality because of a couple of reasons. First, just like any class, it has no concept of missing attributes and an attribute set to None is interpreted by the database driver as null. Second, @dataclass is implemented via auto-generated __init__, so it imposes unreasonable field order to satisfy optional arguments following required ones in the constructor. Lack of an alternative constructor doesn't help either.

EDIT: Replaced self.x_o with self._storage, which was a copy-and-paste error copying examples from a larger test case.

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 việc xem xét tương tác được yêu cầu giữa TypedDict.required_keys, TypedDict.optional_keys và Literal, cùng với ví dụ sử dụng mypy và pymongo. Issue không nêu tên tệp hoặc test nào trong repository; hoàn thành sẽ yêu cầu một design được thống nhất và việc xác thực rằng các tập khóa TypedDict có thể cung cấp thông tin khóa literal cho các thao tác lưu trữ có kiểu.

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
Cần làm rõ
Mức phù hợp với người mới
25/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.