AnyOf - Union for return types
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ả
Sometimes a function or method can return one of several types, depending on the passed in arguments or external factors. Best example is probably open(), but there are other examples in the standard library, like shutil.copy()[1]. In many of those cases, the caller knows what return type to expect.
Currently there are several options, but none of them is really satisfactory:
- Use
@overload. This is the best solution if it can be used. But that is often not the case, like in the examples above. - Use a mypy plugin. This solution does not scale to outside the standard library (and arguably not even inside it) and is mypy-specific.
- Use
Unionas the return type. This is usually not recommended, since it means that the caller needs to useisinstance()to use the return type. - Use
Anyas the return type. This is currently best practice in those cases, but of course provides no type safety at all.
Therefore, I propose to add another type, for example AnyOf[...] that acts like Union, but can be used everywhere any of its type arguments could be used.
from datetime import date
x: AnyOf[str, date] = ...
s: str = x # ok
dt: date = x # ok
i: int = x # type error
u: Union[str, bytes] = x # ok
x = u # type error (although the type checker could do something smart here and infer that u can only be str here)
I also think that the documentation should make it clear that using AnyOf is a code smell.
[1] Currently the type behaviour in shutil is broken in my opinion, but that does not change the fact that currently it is as it is.
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
Đọc đề xuất AnyOf và so sánh các ví dụ của đề xuất—open(), shutil.copy(), Union và @overload—với hành vi hiện tại của typing. Xem lại phần thảo luận của issue để xác định liệu đã có sự thống nhất về ngữ nghĩa và tài liệu hay chưa; được xem là hoàn tất khi có một đặc tả đã được thống nhất, bao quát việc gán cho từng kiểu thành viên, tính tương thích với Union và các kiểu không hợp lệ.
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
- compilers
- 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