Mypy reports invalid type when a value is a parameterized generic
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 I attempt to use a parameterized generic as a value to build a signature at runtime, mypy complains about the parameter as being invalid, when the parameter comes from a variable.
To Reproduce
from inspect import Parameter
def signature_parameter(name: str, item_type: type) -> Parameter:
return Parameter(name=name, kind=Parameter.KEYWORD_ONLY, annotation=list[item_type])
Expected Behavior
I would expect no error in this case (when the parameterized type is used as a value).
I know a variable cannot be used as a type parameter in a typing context (i.e. when used as a type annotation).
I understand that the following code would be wrong because variables cannot be used in type specifications:
var: type = int
lst: list[var] = [1, 2, 3] # this is wrong
But in my case above, list[item_type] is not used as a type specification, but as a value, that is passed to the runtime to build a signature. I do not think mypy should flag such use of values. It should simply consider the value to be of type types.GenericAlias.
Actual Behavior
typing-8.py:6: error: Variable "item_type" is not valid as a type [valid-type]
typing-8.py:6: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases
Found 1 error in 1 file (checked 1 source file)
Your Environment
- Mypy version used:
mypy 1.12.0+dev.6a0657e5959ba1777c4d427f8f355d499035d145 (compiled: no) - Mypy command-line flags: None
- Mypy configuration options from
mypy.ini(and other config files):
[tool.mypy]
enable_incomplete_feature = "NewGenericSyntax"
disable_bytearray_promotion = true
disable_memoryview_promotion = true
check_untyped_defs = true
warn_unreachable = true
warn_redundant_casts = true
warn_unused_ignores = true
- Python version used: 3.12
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 với trình tái hiện typing-8.py và chạy mypy trên Python 3.12 để xác nhận chẩn đoán [valid-type] cho list[item_type]. Truy vết đường dẫn kiểm tra kiểu chịu trách nhiệm cho chẩn đoán đó và thêm một bài kiểm thử hồi quy cho thấy giá trị chú thích thời gian chạy này được chấp nhận; hoàn tất khi bài kiểm thử vượt qua mà không suppress lỗi.
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