python / python/mypy

Metaclass confusion with properties

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

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

bug priority-2-low topic-descriptors topic-metaclasses
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'm using python 3.8 and mypy 0.740. The script below prints "21" and "42" when run, but fails to type check with mypy:

class meta (type):
    pass

class value (metaclass=meta):
    pass


class submeta (meta):
    @property
    def attr(cls) -> int:
        return 42

class subvalue (metaclass=submeta):
    @property
    def attr(self) -> int:
        return 21

o = subvalue()
a = o.attr
print(a)
a = subvalue.attr
print(a)

The mypy diagnostics say:

meta-test.py:24: error: Incompatible types in assignment (expression has type "Callable[[subvalue], int]", variable has type "int")
Found 1 error in 1 file (checked 1 source file)

The error is incorrect, "subvalue.attr" has type "int", as it resolves to the property defined on the metaclass, not to the property defined on the class.

This is fairly esoteric as written, but is the structure used by PyObjC to expose Objective-C classes. PyObjC uses metaclasses to expose class methods because ObjC classes can have instance- and class-methods with the same name.

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

Tái hiện chẩn đoán bằng cách sử dụng ví dụ meta-test.py được mô tả trong issue với Python 3.8 và mypy 0.740. Bắt đầu bằng cách lần theo cách mypy phân giải các thuộc tính trên subvalue so với metaclass submeta của nó. Được xem là hoàn tất khi subvalue.attr được suy luận là int mà không có lỗi incompatible-assignment được báo cáo, trong khi việc truy cập instance vẫn chính xác.

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
Đặc tả rõ ràng
Mức phù hợp với người mới
38/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.