Type confusion with protocol attributes when explicitly subclassing protocol
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ả
Bug Report
When type hinting an attribute on a protocol, and then explicitly subclassing the protocol in a class and performing assignment on the attribute, mypy appears to lose the type information on the attribute. In one case, mypy determines the type is whatever can be inferred from the assignment, and in another case, mypy cannot determine the type.
I've looked at Python's documentation for explicitly subclassing a Protocol (docs) as well as the documentation in mypy for Protocols (docs) and I believe this should work.
To Reproduce
Case 1: Incompatible types in assignment
from typing import Protocol
class InventoryItemProtocol(Protocol):
val: int | None
class InventoryItemMixin(InventoryItemProtocol):
def set(self) -> None:
self.val = 1
class InventoryItem(InventoryItemMixin):
def __init__(self) -> None:
self.val: int | None = None
Case 2: Cannot determine type
from typing import Protocol
class ValProtocol(Protocol):
val: int | None
class Runner(ValProtocol):
def run(self) -> None:
if not self.val:
raise ValueError
self.val = 1
Expected Behavior
Both programs pass type checks.
Actual Behavior
Case 1
sandbox_protocol1.py:15: error: Incompatible types in assignment (expression has type "int | None", base class "InventoryItemMixin" defined the type as "int") [assignment]
Found 1 error in 1 file (checked 1 source file)
Case 2
sandbox_protocol2.py:10: error: Cannot determine type of "val" [has-type]
Found 1 error in 1 file (checked 1 source file)
Your Environment
mypy --version
mypy 1.17.1 (compiled: yes)
python --version
Python 3.12.2
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 chạy hai ví dụ Protocol trong issue với mypy 1.17.1 và so sánh các lỗi với hành vi mong đợi. Theo dõi cách các thuộc tính Protocol được subclass một cách tường minh được suy luận và xác thực; công việc được xem là hoàn tất khi cả hai ví dụ đều vượt qua bước kiểm tra kiểu mà không làm mất kiểu thuộc tính đã khai báo.
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
- Lỗi
- Độ khó
- 4/5
- Thời gian dự kiến
- 3-5 ngày
- 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
- 45/100