Infer type of `attrs.fields(type(attrs_instance))`
Nadie ha tomado este issue todavía.
- Lenguaje dominante
- Python
- Estrellas
- 20.6k
- Forks
- 3.3k
- Métricas de merge de PR
- Métricas de PR pendientes
Descripción
Feature
mypy currently infers the type of attrs.fields(foo) as Any, where foo is an instance of an attrs class. Is it possible to have mypy infer the correct type?
With this setup:
import attrs
from attrs import define
@define
class Foo:
bar: int
foo = Foo(1)
mypy infers the correct type for attrs.fields(Foo):
fields = attrs.fields(Foo)
reveal_type(fields)
reveal_type(fields.bar)
reveal_type(fields.not_bar)
"""
demo.py:13: note: Revealed type is "tuple[attr.Attribute[builtins.int], fallback=demo.Foo.__demo_Foo_AttrsAttributes__]"
demo.py:14: note: Revealed type is "attr.Attribute[builtins.int]"
demo.py:15: error: "__demo_Foo_AttrsAttributes__" has no attribute "not_bar" [attr-defined]
demo.py:15: note: Revealed type is "Any"
Found 1 error in 1 file (checked 1 source file)
"""
but mypy infers attrs.fields(type(foo)) as Any:
fields = attrs.fields(type(foo))
reveal_type(fields)
reveal_type(fields.bar)
reveal_type(fields.not_bar)
"""
demo.py:13: note: Revealed type is "Any"
demo.py:14: note: Revealed type is "Any"
demo.py:15: note: Revealed type is "Any"
Success: no issues found in 1 source file
"""
Pitch
Passing the class to attrs.fields() is the documented usage.
If you pass type(attrs_instance) instead, mypy quietly treats the type as Any (even under strict mode), so it cannot catch attr-defined errors when you access a non-existent field.
Guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Línea de trabajo
Reproduce los dos casos de attrs.fields del issue, incluidas las comprobaciones de reveal_type para fields.bar y fields.not_bar, en strict mode. Sigue el tratamiento que hace mypy de attrs.fields(type(foo)); se considera terminado cuando la forma derivada de la instancia recibe el mismo tipo de campo útil que attrs.fields(Foo) y rechaza el campo inexistente.
Escrito por el modelo de indexación a partir del texto del issue.
Evaluación
- Stack tecnológico
- python
- Área
- tooling
- Tipo de issue
- Nueva funcionalidad
- Dificultad
- 3/5
- Tiempo estimado
- 1-2 días
- Estado de actividad
- Estancado
- Claridad
- Bastante claro
- Aptitud para principiantes
- 42/100