Request: an AssertingTypeGuard type for TypeGuard-like semantics
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ả
There is a frequent pattern of TypeGuard-like functions which assert or otherwise raise an exception if a type constraint is not met.
For example, https://github.com/microsoft/pyright/issues/2007 points to a case in which unittest provides assertIsNotNone, but a type-checker cannot infer that type narrowing has occurred. Arguably, the popular typeguard library is based around an implementation of "asserting" type guards. (One which deduces what assertions should be made from the annotations.)
TypeGuards allow for semantics like
y: str
assert is_list_of_str(x)
assert len(x) > 0
y = x[0]
An AssertingTypeGuard would allow for
y: str
assert_is_nonempty_list_of_str(x) # note, this encodes another runtime check, the len check
y = x[0]
This becomes especially valuable if we consider that you might not want to do this all with assert. I may, as an author, prefer my own custom exceptions, e.g.
def assert_is_nonempty_list_of_str(x) -> AssertingTypeGuard[list[str]]:
if not isinstance(x, list):
raise ExpectedListError(x)
if not x:
raise EmptyContainerError(x)
if not all(isinstance(y, str) for y in x):
raise ContainedInvalidTypeError(x, str)
return x
(Apologies if this repo is the wrong place to submit this request/idea. I'm happy to go through another process if necessary.)
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
Yêu cầu không xác định các tệp triển khai hoặc kiểm thử. Hãy bắt đầu bằng việc xem xét các ví dụ TypeGuard, issue Pyright được liên kết và cuộc thảo luận về thư viện typeguard; xác định liệu một AssertingTypeGuard có thuộc đặc tả typing hay không, đồng thời định nghĩa ngữ nghĩa narrowing và ngoại lệ được mong đợi trước khi triển khai.
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
- Ít trao đổi
- Độ rõ ràng
- Khá rõ ràng
- Mức phù hợp với người mới
- 35/100