python / python/mypy

False negative: potentially unbound instance attribute doesn't trigger `possibly-undefined` error

Đang mở
#17,837 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
Chỉ số merge pull request
Chỉ số pull request đang chờ

Mô tả

Bug Report

When enabling the possibly-undefined error code, a potentially undefined instance attribute doesn't trigger the error, while a potentially unbound variable does.

To Reproduce

def test_possibly_undefined(flag: bool):
    if flag:
        a = 1
    print(a)  # error: Name "a" may be undefined  [possibly-undefined]


class Foo:
    def test_possibly_undefined(self, flag: bool):
        if flag:
            self.a = 1
        print(self.a)  # false negative, should also be a possibly-undefined error


try:
    test_possibly_undefined(False)
except Exception as e:
    print(f"{type(e).__name__}: {e}")  # UnboundLocalError: cannot access local variable 'a' where it is not associated with a value

f = Foo()
try:
    f.test_possibly_undefined(False)
except Exception as e:
    print(f"{type(e).__name__}: {e}")  # AttributeError: 'Foo' object has no attribute 'a'

Also available as mypy Playground, but cannot enable enable_error_code = possibly-undefined there.

Expected Behavior

A possible-undefined error should be reported for line 11 as well, e.g.:

test.py:4: error: Name "a" may be undefined  [possibly-undefined]
test.py:11: error: Attribute "a" may be undefined  [possibly-undefined]
Found 2 errors in 1 file (checked 1 source file)

Actual Behavior

No error reported for line 11.

test.py:4: error: Name "a" may be undefined  [possibly-undefined]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.11.2
  • Mypy command-line flags: --enable-error-code=possibly-undefined
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.12.6

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 tái hiện ví dụ với mypy 1.11.2 và mã lỗi possibly-undefined, sau đó tìm logic của checker và các bài kiểm thử hồi quy cho các biến cục bộ có thể chưa được định nghĩa. So sánh cách xử lý tên cục bộ với thuộc tính instance và bổ sung coverage cho ví dụ Foo; hoàn tất khi mypy báo lỗi dự kiến Attribute "a" may be undefined.

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

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.