python / python/typing

[spec] Formalize excluded Protocol members

Đang mở
#1,833 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.

topic: documentation
Ngôn ngữ chính
Python
Star
1.8k
Fork
302
Merge trung bình
23 giờ
Pull request đã merge (30 ngày)
8

Mô tả

At runtime, the following members are currently excluded by Protocol: (source)

_TYPING_INTERNALS = frozenset({
    '__parameters__', '__orig_bases__',  '__orig_class__',
    '_is_protocol', '_is_runtime_protocol', '__protocol_attrs__',
    '__non_callable_proto_members__', '__type_params__',
})


_SPECIAL_NAMES = frozenset({
    '__abstractmethods__', '__annotations__', '__dict__', '__doc__',
    '__init__', '__module__', '__new__', '__slots__',
    '__subclasshook__', '__weakref__', '__class_getitem__',
    '__match_args__', '__static_attributes__', '__firstlineno__',
    '__annotate__',
})


# These special attributes will be not collected as protocol members.
EXCLUDED_ATTRIBUTES = _TYPING_INTERNALS | _SPECIAL_NAMES | {'_MutableMapping__marker'}

However, neither PEP 544 nor the typing spec formalize this list, which leads to diverging behavior between different type checkers:

Code sample in pyright playground, mypy playground

from typing import TypeIs, Protocol

class MyProtocol(Protocol):
    @classmethod
    def __subclasshook__(cls, other: type, /) -> TypeIs[type["MyProtocol"]]:
        ...

x: MyProtocol = int(1)  # mypy: ✅ pyright: ❌

Code sample in pyright playground, mypy playground

from typing import Protocol

class MyProtocol(Protocol):
    __abstractmethods__: frozenset[str]
    
x: MyProtocol = int(1)  # mypy: ✅ pyright: ❌

A real-world example where this matters is for instance a Protocol for NamedTuple Instances, that checks whether types.get_original_bases(cls) includes typing.NamedTuple inside __subclasshook__.

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

Chưa lập chỉ mục được hướng dẫn đóng góp cho kho mã nguồn này

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 với định nghĩa EXCLUDED_ATTRIBUTES trong Lib/typing.py và so sánh nó với PEP 544, typing specification cùng các ví dụ được liên kết của pyright và mypy. Xác định những thành viên Protocol nào cần đặc tả chính thức và ghi lại hành vi dự kiến để các kết quả khác nhau của các checker có cách giải quyết rõ ràng.

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
documentation
Loại issue
Tài liệu
Độ khó
5/5
Thời gian dự kiến
Hơn một tuần
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

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.