python / python/mypy

Checking elements of a `list[str | None]` after discarding the possibility of `None`

Đang mở
#16,243 2 bình luận 0 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

bug
Ngôn ngữ chính
Python
Star
20.6k
Fork
3.3k
Merge trung bình
1 ngày 18 giờ
Pull request đã merge (30 ngày)
54

Mô tả

Bug Report

str_none: list[str | None]
only_str: list[str]
for i in range(len(sequence)):
    if sequence[i] is not None:
        only_str.append(sequence[i]) # Here mypy raises an error due to "incompatible types"

The code above raises the following error Argument 1 to "append" of "list" has incompatible type "str | None"; expected "str".

I've found the following verbose workaround but to my taste its :

str_none: list[str | None]
only_str: list[str]
for i in range(len(sequence)):
    element = sequence[i]
    if element is not None:
        only_str.append(element)

To Reproduce

See code example above.

Expected Behavior

I'm expecting mypy to be able to predict future annotations of sequences with multiple types possible after discarding a specific type in a condition.

Actual Behavior

All is included above.

Your Environment

  • Mypy version used: 1.5.1
  • Mypy command-line flags: both --strict and none
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.11.5

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. 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.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. 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 trình tái hiện tối thiểu từ issue với mypy 1.5.1, sau đó theo dõi hành vi thu hẹp kiểu đối với việc truy cập chuỗi bằng chỉ mục. Công việc được coi là hoàn tất khi ví dụ chấp nhận phần tử đã được thu hẹp mà không cần workaround biến cục bộ dài dòng, với một bài kiểm thử hồi quy bao quát trường hợp đã báo cá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ó
3/5
Thời gian dự kiến
1-2 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
42/100

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.