Support generic upper bounds
Chưa có ai nhận issue này.
- Ngôn ngữ chính
- Python
- Star
- 20.6k
- Fork
- 3.3k
- Chỉ số merge pull request
- Chỉ số pull request đang chờ
Mô tả
Feature
Allow generic upper bounds such as:
class ClassA[T, S: Sequence[T]]: ...
Pitch
PEP 695 has an example that currently doesn't work, and alludes to a future extension to the typesystem that eliminates the limitation:
# The following generates no compiler error, but a type checker
# should generate an error because an upper bound type must be concrete,
# and ``Sequence[S]`` is generic. Future extensions to the type system may
# eliminate this limitation.
class ClassA[S, T: Sequence[S]]: ...
I ran into a usecase for this that I have no way of expressing with the current generics limitations, and generic upper bounds would solve it. I will provide a simpler version of it here so it's easier to discuss.
from typing import Callable, Iterable, Sequence
type CostFunction[T] = Callable[[T], float]
# Sequence[T] gives an error, because T is not concrete
def get_lowest_cost_sequence[T, S: Sequence[T]](
seqs: Iterable[S], item_cost: CostFunction[T]
) -> S:
def seq_cost(seq: S) -> float:
return sum(item_cost(t) for t in seq)
return sorted(seqs, key=seq_cost)[0]
In the example, we are working with sequences, and a cost function for each item in the sequences. The crux is that the function must return the same type as the original sequences. In other words this is an incorrect type signature:
# Return type Sequence[T] is looser, because it does not mean whatever is
# returned will be _the same type_ as what is passed in. Any users of this
# function would have to cast the result for it to expose the same functionality
# as what was in `seqs`.
def get_lowest_cost_sequence[T](
seqs: Iterable[Sequence[T]], item_cost: CostFunction[T]
) -> Sequence[T]:
...
Hướng dẫn đóng góp
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
Không có tệp triển khai, bài kiểm thử hoặc điểm vào nào được nêu. Hãy bắt đầu với phần type-parameter-scopes của PEP 695 và các ví dụ trong Issue này, sau đó lần theo cách mypy xử lý các cận trên generic; được xem là hoàn tất khi các cận generic hợp lệ được chấp nhận, còn các cận không cụ thể không hợp lệ vẫn bị từ chối, kèm theo độ bao phủ hồi quy.
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
- Khá rõ ràng
- Mức phù hợp với người mới
- 35/100