python / python/mypy

Meta issue: better `getattr` support

Abierto
#11,142 2 comentarios 12 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

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

Descripción

Feature

One thing that bothered me for a long time is getattr and its very broad return type even for simplest cases:

from typing import Literal

class Some:
    def __init__(self) -> None:
        self.a = 1

s = Some()

reveal_type(s.a)  # Revealed type is "builtins.int"
reveal_type(getattr(s, 'a'))  # Revealed type is "Any"
reveal_type(getattr(s, 'b'))  # Revealed type is "Any"
reveal_type(getattr(s, 'a', None))  # Revealed type is "Union[Any, None]"

a: Literal['a']
reveal_type(getattr(s, a))  # Revealed type is "Any"

ab: Literal['a', 'b']
reveal_type(getattr(s, ab))  # Revealed type is "Any"

So, I propose to add better support for it to mypy.

The same example, after the support is added:

from typing import Literal

class Some:
    def __init__(self) -> None:
        self.a = 1

s = Some()

reveal_type(s.a)  # Revealed type is "builtins.int"
reveal_type(getattr(s, 'a'))  # Revealed type is "builtins.int"
reveal_type(getattr(s, 'b'))  # error: "Some" has no attribute "b"
reveal_type(getattr(s, 'a', None))  # Revealed type is "builtins.int"

a: Literal['a']
reveal_type(getattr(s, a))  # Revealed type is "builtins.int"

ab: Literal['a', 'b']
reveal_type(getattr(s, ab))  # error: "Some" has no attribute "b"
reveal_type(getattr(s, ab, None))  # Revealed type is "builtins.int | None"

I have even written a custom plugin for it at some point.

Why?

This pattern is quite popular among Python developers. geattr(obj, 'string_key', None) is used for compatibility, optional dependencies, etc. That's something you can find in almost any project.

Technical details

I am going to utilize existing checkmember logic.
I even plan to support attribute plugins, where possible, because a.x and getattr(a, 'x') are semantically identical.
For now only str literals and Literal str types are going to be supported.

Related issues and problems

I am calling this issue "meta", because there are several very related problems I want to mention / solve here:

Next steps

I will start with a PR with a code prototype in a couple of days.

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 leyendo la lógica existente de checkmember a la que se hace referencia en el issue y revisa los issues relacionados 1424 y 10409. Compara los ejemplos solicitados de getattr, incluidos los nombres de tipo string y Literal y los valores predeterminados, y usa los resultados de reveal_type y los errores de atributos faltantes indicados como criterios de finalización.

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

Evaluación

Stack tecnológico
python
Área
devtools
Tipo de issue
Nueva funcionalidad
Dificultad
5/5
Tiempo estimado
Más de una semana
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
35/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.