python / python/typeshed

Several methods on built-in types are too strict.

Đang mở
#15,271 4 bình luận 3 reaction 0 người được giao Xem trên GitHub

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

Ngôn ngữ chính
Python
Star
5.1k
Fork
2.1k
Merge trung bình
1 ngày 19 giờ
Pull request đã merge (30 ngày)
82

Mô tả

I have identified several methods on built-in types that are too strict and can cause annoying false positives:

  • set and frozenset methods (#15470, #15160)
  • dict.{get, pop} (#15471)
  • list.{count, index, remove} (#15472)
  • MutableSet.discard
  • Mapping.get
  • MutableMapping.pop
  • Sequence.{count, index}
  • MutableSequence.remove
  • probably some more.

It seems like the annotations for these were designed to help detect user errors. For instance, we know that .get on a dict[int, int] will always return the default as the types are incompatible, and so .get was restricted in typeshed to only accept the key type. However, this hurts, even in simple cases like using literals:

from typing import Mapping, Literal

def demo_get(
    d: Mapping[Literal["foo", "bar"], int],
    dynamic_key: str,
) -> None:
    # No overload variant of "get" of "Mapping" matches argument type "str"
    d.get(dynamic_key)  

def demo_sub(
    left: set[Literal["foo", "bar"]],
    right: set[str],
) -> None:
    # Unsupported operand types for - ("set[Literal['foo', 'bar']]" and "set[str]")
    left - right

I believe typeshed is trying to act as a linter here, which shouldn't be its job. Type-checkers and type-informed linters are better at this and can use more complex logic.

For example, in the set difference case set[A] - set[B], the proper test would be to check whether the types have a non-empty intersection or not. The same could be said for Mapping[K, V].get(K2).

Related Topics:

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 xác định các stub của typeshed cho những phương thức dict, list, set, Mapping, Sequence và Mutable* đã nêu, sau đó đọc các issue liên quan 8219, 9155 và 9004. Phạm vi vẫn chưa được thống nhất vì issue cũng đề cập đến khả năng có thêm các phương thức khác; để được coi là hoàn tất, cần thống nhất tập hợp các API bị ảnh hưởng và thực hiện các thay đổi nhất quán đối với annotation.

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
tooling
Loại issue
Tính năng
Độ khó
5/5
Thời gian dự kiến
Hơn một tuần
Mức độ hoạt động
Ít trao đổi
Độ rõ ràng
Cần làm rõ
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.