python / python/mypy

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

Abierto
#17,514 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

bug
Lenguaje dominante
Python
Estrellas
20.6k
Forks
3.3k
Métricas de merge de PR
Métricas de PR pendientes

Descripción

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.

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Empieza ejecutando el reproductor plugin.py y module.py con las versiones de Python y mypy indicadas, y luego sigue el análisis de tipos de Annotated en uso directo, de TypeAlias y de la especialización genérica. Se considera terminado cuando el hook se invoca en los tres casos y cada reveal_type informa de None, tal como solicita _type_analyze.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
python
Área
devtools
Tipo de issue
Error
Dificultad
3/5
Tiempo estimado
1-2 días
Estado de actividad
Estancado
Claridad
Bien especificado
Aptitud para principiantes
48/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.