python / python/mypy

Decorated __init__ confuses callback type if decorator is defined with type alias or if decorator is imported using relative import

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

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

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

説明

This one's just weird. I'm not sure if this is a dup of #1927, but I figured I'd raise it anyway.

# test_case.py
from typing import Callable, Iterable, TypeVar, Union

_T = TypeVar("_T")

def _identity(__: _T) -> _T:
    return __

# decr: Callable[[_T], _T] = _identity  # <-- this approach works
DecoratorT = Callable[[_T], _T]
decr: DecoratorT = _identity  # <-- this causes the false positives below

class Result:
    @decr
    def __init__(self):
        pass

res = Result()  # ; reveal_type(res)  # -> Any (should be test_case.Result)

def some_results(op: Callable[[], Union[Result, Iterable[Result]]]) -> Iterable[Result]:
    result_or_results = op()
    results: Iterable[Result]
    if isinstance(result_or_results, Result):
        results = (result_or_results,)  # ; reveal_type(result_or_results)  # -> (should be test_case.Result)
    else:
        results = result_or_results  # ; reveal_type(result_or_results)  # -> Union[test_case.Result, typing.Iterable[test_case.Result]] (should be typing.Iterable[test_case.Result])
    return results
% python --version ; mypy --version
Python 3.9.7
mypy 0.910
% mypy --config-file=pyproject.toml test_case.py
test_case.py:26: error: Incompatible types in assignment (expression has type "Union[Result, Iterable[Result]]", variable has type "Iterable[Result]")
Found 1 error in 1 file (checked 1 source file)

Note that if DecoratorT is defined as follows, things work again:

# …
class DecoratorT(Protocol):
    def __call__(self, __: _T) -> _T:
        ...
decr: DecoratorT = _identity  # <-- all good
# …

But if we move the decorator into its own module and use a relative import, it breaks no matter how we define the decorator type:

# test_case.py
from typing import Callable, Iterable, TypeVar, Union
# from test_case_import import decr  # <-- this works
from .test_case_import import decr  # <-- this causes the false positives below 

class Result:
    @decr
    def __init__(self):
        pass

res = Result()  # ; reveal_type(res)  # -> Any (should be test_case.Result)

def some_results(op: Callable[[], Union[Result, Iterable[Result]]]) -> Iterable[Result]:
    result_or_results = op()
    results: Iterable[Result]
    if isinstance(result_or_results, Result):
        results = (result_or_results,)  # ; reveal_type(result_or_results)  # -> (should be test_case.Result)
    else:
        results = result_or_results  # ; reveal_type(result_or_results)  # -> Union[test_case.Result, typing.Iterable[test_case.Result]] (should be typing.Iterable[test_case.Result])
    return results
# test_case_import.py
from typing import Callable, TypeVar
_T = TypeVar("_T")

def _identity(__: _T) -> _T:
    return __

decr: Callable[[_T], _T] = _identity  # <-- doesn't matter how this is defined
% mypy --config-file=pyproject.toml test_case.py test_case_import.py
test_case.py:19: error: Incompatible types in assignment (expression has type "Union[Result, Iterable[Result]]", variable has type "Iterable[Result]")
Found 1 error in 1 file (checked 2 source files)

Using the Protocol approach does not salvage the second (relative import) scenario.

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

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

はじめの一歩

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

調査の方向性

まず、test_case.py と test_case_import.py で mypy を使って報告された診断を再現し、ローカルな decorator の場合と相対インポートした decorator の場合を比較します。mypy が装飾された init とインポートされた decorator の型をどのように推論するかを追跡します。例が注釈どおりに Result と Iterable[Result] を推論し、誤った assignment error の false positive が発生しなければ完了です。

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

評価

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

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

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