Allow use of `Required` and `NotRequired` to make an existing typed dict total or optional
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ả
I think the ability of indicating that a typed dict requires all keys or that all are optional would be very useful.
For example to allow defining default values for a particular dict or to return a dict that has been completely assigned from a function
A simple example
class A(TypedDict):
a: int
b: int
ADefault = {'a': 1, 'b': 42}
def optionalA(v: NotRequired[A]) -> A:
return ADefault | v
optionalA({'a': 11}) # ok since all keys of NotRequired[A] are optional
class X(TypedDict, total=False):
x: str
y: str
XDefault: X = {"x": "xv", "y": "yv"}
def withXDefault(v: X) -> Required[X]:
return XDefault | v
withXDefault({"x": "foo"})["y"] # ok since all keys of Required[X] are required
This idea is inspired by the analogous types in typescript Required and Partial that are in general very convenient.
I think it makes sense having the same behaviour of the typescript counterparts:
NotRequired[X]is a no op, since X is defined astotal=False. Same forRequired[A].Required/NotRequiredwould include all keys of the typed dict and all its superclasses. This differs from howtotalworks. Example:class TD1(TypedDict): a: int class TD2(TypedDict, total=False): b: int TDR = Required[TD2] # b becomes required TDNR = NotRequired[TD2] # a becomes not requiredRequired/NotRequiredused inline in the TypedDict are not taken into consideration, so the end result is the same independently of how the typed dict is defined
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 bằng cách xem xét ngữ nghĩa được đề xuất của TypedDict, Required và NotRequired cùng các ví dụ trong issue, bao gồm tính kế thừa và các chú thích inline. Xác định hành vi và các typing specification cũng như các bài kiểm tra tính phù hợp có liên quan; hoàn tất có nghĩa là các phép biến đổi được yêu cầu đã được đặc tả và xác thực một cách nhất quán.
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
- developer-experience
- 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