Having to add type hint 2nd time on AnyStr when assigning as instance attribute
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ả
I am reporting a potential bug/improvement in mypy.
I assign a class's instance attribute to be an argument from the __init__ signature.
I noticed that when the argument is type hinted as a AnyStr, mypy raises an error unless the instance attribute receives a second type hint.
from typing import AnyStr, Generic
class A(Generic[AnyStr]):
def __init__(self, arg: AnyStr):
# Case A... error: Need type annotation for 'attr'
self.attr = arg
reveal_type(arg)
# note: Revealed type is 'builtins.str*'
# note: Revealed type is 'builtins.bytes*'
reveal_type(self.attr)
# note: Revealed type is 'builtins.str'
# note: Revealed type is 'Any'
# Observation: 'builtins.bytes*' doesn't seem to propagate
class B(Generic[AnyStr]):
def __init__(self, arg: AnyStr):
# Case B... Success
self.attr = arg # type: AnyStr
The desirable behavior is not to have to supply a second type hint.
What's going on here? Is there some way I can not supply a second type hint?
I am invoking mypy from the command line with no flags. Here are my versions:
python==3.6.5
mypy==0.770
Aside
I am coming here from Stack Overflow, where a community member thought it was a bug: Python mypy why does class instance attribute require type hint if expression already has type hint
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 tái hiện vấn đề từ đoạn mã Python đi kèm với mypy 0.770, so sánh Case A và Case B cùng các kiểu được revealed của chúng. Theo dõi việc suy luận thuộc tính của instance đối với Generic[AnyStr] và xác định xem biến kiểu có nên được truyền tiếp mà không cần chú thích inline hay không. Công việc được xem là hoàn tất khi Case A không còn yêu cầu gợi ý kiểu thứ hai và có kiểm thử hồi quy bao phủ hành vi đã nêu.
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
- 35/100