python / python/typeshed

Several methods on built-in types are too strict.

オープン
#15,271 コメント 4 件 リアクション 3 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

主要言語
Python
スター
5.1k
フォーク
2.1k
平均マージ
1日 19時間
マージ済み PR(30日)
82

説明

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:

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

まず、列挙されている dict、list、set、Mapping、Sequence、Mutable* の各メソッドに対応する typeshed のスタブを見つけ、関連する Issue 8219、9155、9004 を読んでください。Issue では追加のメソッドも含まれる可能性があると述べられているため、対象範囲はまだ確定していません。完了とするには、影響を受ける API の対象集合について合意し、アノテーションを一貫して変更する必要があります。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
tooling
issue の種類
機能追加
難易度
5/5
見積もり時間
1週間以上
活発さ
静か
明瞭さ
説明が足りない
初心者へのやさしさ
35/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。