python / python/mypy

Having to add type hint 2nd time on AnyStr when assigning as instance attribute

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

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

主要言語
Python
スター
20.6k
フォーク
3.3k
PR マージ指標
PR 指標を取得中

説明

I am reporting a potential bug/improvement in mypy.

I assign a class's instance attribute to be an argument from the __init__ signature.

I noticed that when the argument is type hinted as a AnyStr, mypy raises an error unless the instance attribute receives a second type hint.

from typing import AnyStr, Generic


class A(Generic[AnyStr]):
    def __init__(self, arg: AnyStr):
        # Case A... error: Need type annotation for 'attr'
        self.attr = arg

        reveal_type(arg)
        # note: Revealed type is 'builtins.str*'
        # note: Revealed type is 'builtins.bytes*'

        reveal_type(self.attr)
        # note: Revealed type is 'builtins.str'
        # note: Revealed type is 'Any'
        # Observation: 'builtins.bytes*' doesn't seem to propagate


class B(Generic[AnyStr]):
    def __init__(self, arg: AnyStr):
        # Case B... Success
        self.attr = arg  # type: AnyStr

The desirable behavior is not to have to supply a second type hint.

What's going on here? Is there some way I can not supply a second type hint?


I am invoking mypy from the command line with no flags. Here are my versions:

python==3.6.5
mypy==0.770

Aside

I am coming here from Stack Overflow, where a community member thought it was a bug: Python mypy why does class instance attribute require type hint if expression already has type hint

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

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

はじめの一歩

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

調査の方向性

まず、含まれている Python スニペットを mypy 0.770 で実行して問題を再現し、Case A と Case B、およびそれぞれで明らかになる型を比較します。Generic[AnyStr] に対するインスタンス属性の推論を追跡し、インラインアノテーションなしで型変数が伝播されるべきかどうかを判断します。Case A で 2 つ目の型ヒントが不要になり、示された動作に対するリグレッションテストのカバレッジが追加されれば完了です。

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

評価

技術スタック
python
領域
devtools
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

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

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