python / python/typing

Assuming `self` or `cls` parameter is positional-only

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

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

topic: other
主要言語
Python
スター
1.8k
フォーク
302
平均マージ
23時間
マージ済み PR(30日)
8

説明

I'm interested in guidance from the typing community relating to a question that came up in a recent pyright bug report.

The issue has to do with the self parameter in an instance method and the cls parameter in a class method — whether a type checker should assume that they are implicitly positional-only parameters. In particular, the discussion was about method declarations within a protocol class.

PEP 570 makes a reference to this topic in its introductory section:

One special case of this situation is the self parameter for class methods: it is undesirable that a caller can bind by keyword to the name self when calling the method from the class.

But PEP 570 doesn't provide any specific guidance about self or cls in its specification section. PEP 544 (which introduced protocols) is also silent on the topic.

Pyright currently assumes that self and cls are not positional-only parameters (unless explicitly followed by a / parameter marker or named with double underscores). This assumption affects protocol matching — and more generally, subtype compatibility evaluation for callables.

@AlexWaygood is proposing that the first parameter of instance and class methods should always be considered position-only parameters.

This raises some questions in my mind:

  1. Is this a safe assumption? Does anyone know of a situation where self or cls are used as keyword arguments?
  2. Does this apply only to protocol methods, or does it apply generally to methods in any class?
  3. Should it be considered a type checker error if someone attempts to use a keyword argument to target the first parameter of an instance or class method? It works at runtime.
class Foo:
    def bar(self): pass

Foo.bar(self=Foo())
  1. Does the cls exemption apply only to explicit class methods, or does it also apply to __new__ and __init_subclass__?

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

このリポジトリのコントリビューションガイドは索引されていません

はじめの一歩

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

調査の方向性

まず PEP 570 と PEP 544 を読み、次にリンク先の Pyright バグレポートと issue の議論を確認します。メソッド、プロトコル、newinit_subclass について、self と cls を位置専用として扱うべきかどうかを判断します。文書化されたコミュニティガイダンスまたは仕様上の決定に到達すれば完了です。

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

評価

技術スタック
python
領域
tooling
issue の種類
ドキュメント
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
説明が足りない
初心者へのやさしさ
20/100

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

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