Feature request: flag attributes set in `__init__` but not `__setstate__`

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

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

評価

難易度
5/5
見積もり時間
1週間以上
初心者へのやさしさ
35/100
issue の種類
機能追加
明瞭さ
おおむね明確
活発さ
停滞
技術スタック
python
領域
devtools

調査の方向性

まず mypy --strict x.py を使って x.py の例を再現し、次に mypy が初期化メソッドとシリアライズメソッドをどのようにモデル化しているかを調べます。__setstate__ に示されている不足している代入によって適切な診断が生成され、かつ有効な一時属性が引き続きサポートされれば完了です。

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

説明

feature

Feature

If an instance attribute is defined in __init__ but its definition is missing from __setstate__, this could cause a crash when an object is deserialized and the attribute is accessed.

Pitch

import pickle

class A:
    """
    Attribute `a` is persistent and serialized.
    Attribute `b` is temporary and not serialized.
    """
    def __init__(self) -> None:
        self.a: int = 1
        self.b: int = 2

    def sum(self) -> int:
        return self.a + self.b

    def __getstate__(self) -> tuple[int]:
        return (self.a,)

    def __setstate__(self, state: tuple[int]) -> None:
        self.a = state[0]
        # BUG: self.b is not set

if __name__ == '__main__':
    a = A()
    print(a.sum())
    b = pickle.loads(pickle.dumps(a))
    print(b.sum())  # AttributeError
$ mypy --version
mypy 1.4.1 (compiled: yes)
$ mypy --strict x.py
Success: no issues found in 1 source file

This bug pattern has bitten me multiple times. Especially in cases where serialization is rare and the test cases that stress class interfaces are not performing deserialization, this bug can make it into releases undetected. This seems like a great candidate for a bug to catch with static analysis. It seems appropriate for mypy because it is in some sense a type bug - if we're using the type model where __init__ is supposed to fully initialize a typed interface, then __setstate__ should do the same.

主要言語
Python
スター
20.6k
フォーク
3.3k
平均マージ
1日 18時間
マージ済み PR(30日)
54

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

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

はじめの一歩

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

python/mypy のほかの issue

python/mypy の issue をすべて見る

似ている issue

Python の issue をもっと見る

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

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