Definition of `str.split`, `str.rsplit` and `str.splitlines` results in false positive errors
Chưa có ai nhận issue này.
- Ngôn ngữ chính
- Python
- Star
- 5.1k
- Fork
- 2.1k
- Merge trung bình
- 1 ngày 19 giờ
- Pull request đã merge (30 ngày)
- 82
Mô tả
I recently fixed a bug in pyright that caused a false negative when attempting to assign a list[LiteralString] to a list[str]. As we know, the type parameter for list is invariant, so these types are not consistent.
from typing import LiteralString
v1: list[LiteralString] = ["a", "b"]
v2: list[str] = v1 # Should be a type violation
With this bug fix now in place, the definitions for the methods str.split, str.rsplit and str.splitlines are problematic. These three methods are defined using overloaded signatures, and the first overload returns list[LiteralString]. This means the following code now results in a type violation.
def process(x: list[str]) -> str:
return " ".join(x)
process("1,2,3".split(",")) # Type violation
This is going to generate a lot of new type errors in existing code bases.
I initially attempted to work around this by adding a heuristic in pyright's overload matching logic so it deprioritized the first overload in this case, but this heuristic broke other code and really isn't sound. I've therefore decided to remove the heuristic.
I don't have any good ideas about how to fix this, but I wanted to open the issue to start the discussion to see if anyone had a suggestion. If we're going to fix it, I think the fix needs to be in the typeshed stubs. I don't see a way to fix this in a type checker — at least while remaining true to the type system.
One possible solution is to omit the LiteralString overloads for these three methods. This would eliminate the type violation error in the common case, but it would introduce new errors in cases where callers expect to see a return result of list[LiteralString].
Note that this doesn't currently affect mypy users because mypy has not implemented support for LiteralString.
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
Bắt đầu bằng cách xem xét các định nghĩa quá tải của typeshed cho str.split, str.rsplit và str.splitlines, tập trung vào các kiểu trả về LiteralString của chúng. Sử dụng các ví dụ trong issue để tái hiện các lỗi bất biến của danh sách và đánh giá các phương án thay thế được thảo luận. Hoàn thành khi các cảnh báo dương tính giả được giải quyết mà không làm suy yếu các kết quả LiteralString 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
- tooling
- Loại issue
- Lỗi
- Độ 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