python / python/mypy

Plugin's get_type_analyze_hook is not used for Annotated type in type alias or generic specialization

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

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

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

説明

Bug Report

Mypy doesn't use plugin's get_type_analyze_hook for Annotated type used in type alias or generic specialization. However, the hook is used for custom types (not Annotated) used in these contexts, and it's also called for Annotated used in other contexts.

To Reproduce

plugin.py

from typing import Callable

from mypy.plugin import AnalyzeTypeContext, Plugin
from mypy.types import NoneType, Type

def plugin(version: str):
    return MyPlugin

class MyPlugin(Plugin):
    def get_type_analyze_hook(self, fullname: str) -> Callable[[AnalyzeTypeContext], Type] | None:
        if fullname in {'typing.Annotated', 'typing_extensions.Annotated'}:
            return _type_analyze
        return None

def _type_analyze(ctx: AnalyzeTypeContext) -> Type:
    ctx.api.note('Analyzing type of Annotated[...]', ctx.context)
    return NoneType()  # for the sake of example

module.py

from typing import Annotated, Generic, TypeAlias, TypeVar, reveal_type

AnnotatedTA: TypeAlias = Annotated[dict, None]
typed_with_alias: AnnotatedTA
reveal_type(typed_with_alias)  # Revealed type is "builtins.dict[Any, Any]"

typed_directly: Annotated[dict, None]  # Analyzing type of Annotated[...]
reveal_type(typed_directly)  # Revealed type is "None", as expected


T = TypeVar('T')

class GenericType(Generic[T]):
    dummy: T

class Specialization(GenericType[Annotated[dict, None]]):
    ...

reveal_type(Specialization().dummy)  # Revealed type is "builtins.dict[Any, Any]"

Expected Behavior

All revealed types are None as requested by _type_analyze hook

Actual Behavior

Only directly typed variable typed_directly has the type requested by plugin

Your Environment

  • Mypy version used: 1.10.1
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): plugins = plugin.py
  • Python version used: 3.8, 3.12

Background

I'm writing a plugin which generates TypedDictType for Annotated[dict, ...] annotations based on some external configuration files. The arguments to Annotated are string literals, so I can't really use generics. In runtime these are just normal dicts.

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

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

はじめの一歩

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

調査の方向性

まず、報告されている Python と mypy のバージョンで plugin.py と module.py の再現コードを実行し、次に直接使用時の Annotated、TypeAlias、およびジェネリック特殊化について型解析を追跡します。完了条件は、3 つすべてのケースで hook が呼び出され、各 reveal_type が _type_analyze の要求どおり None を報告することです。

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

評価

技術スタック
python
領域
devtools
issue の種類
バグ
難易度
3/5
見積もり時間
1〜2日
活発さ
停滞
明瞭さ
明確に書かれている
初心者へのやさしさ
48/100

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

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