python / python/mypy

Errors from class decorators returning descriptors

Abierto
#13,862 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

When using a decorator on a nested class that returns a descriptor, mypy is not able to properly distinguish between the class and the instance. The full code is in the gist with the snippets below trying to highlight the problem.

https://gist.github.com/adam-ring/86dc9239fd54e2eafe07829329f39a0d

@overload
def add_register(cls: None = ...) -> RegDescpr[Register]:
    ...
@overload
def add_register(cls: type[T]) -> RegDescpr[T]:
    ...
def add_register(cls: type[T] | None = None) -> RegDescpr[T]:
    return RegDescpr[T](cls)


class FooBlock(RegBlock):

    BAR = add_register()

    @add_register
    class BAZ(Register):
        A = FieldDescpr()
        B = FieldDescpr()

    class BOO_CLS(Register):
        C = FieldDescpr()
    BOO = add_register(BOO_CLS)

foo = FooBlock()

Both foo.BAR and foo.BOO show no errors and run correctly. foo.BAZ lists errors with attribute or method access as will be shown below.

To Reproduce

The method access tests are shown here. Python runs as expected from all three, but mypy complains about an unbound self when accessing foo.BAZ.

foo = FooBlock()
print(f'{foo.BAR.reg_func()=}')  # no error
print(f'{foo.BAZ.reg_func()=}')  # ERROR: reg_func has unbound self
print(f'{foo.BOO.reg_func()=}')  # no error

Expected Behavior

Python runs with all test cases. Here is the output when the gist is run with Python.

$ python3 test_class_dec.py 
Register(name=BAR, RegBlock=FooBlock())
BAZ(name=BAZ, RegBlock=FooBlock())
BOO_CLS(name=BOO, RegBlock=FooBlock())
RegField(name=B, Register=BAZ(name=BAZ, RegBlock=FooBlock()))
RegField(name=C, Register=BOO_CLS(name=BOO, RegBlock=FooBlock()))
foo.BAR.reg_func()=42
foo.BAZ.reg_func()=42
foo.BOO.reg_func()=42
foo.BAZ.A()=5
foo.BOO.C()=5

Actual Behavior

Here is the output from mypy. Only foo.BAZ shows any errors in mypy, the class with the descriptor. The errors are present with method access and with the lower lever Field Descriptor access.

$ mypy test_class_dec.py 
test_class_dec.py:121: error: No overload variant of "__get__" of "FieldDescpr" matches argument types "None", "Type[BAZ]"
test_class_dec.py:121: note: Possible overload variants:
test_class_dec.py:121: note:     def __get__(self, obj: None, objtype: None) -> FieldDescpr
test_class_dec.py:121: note:     def __get__(self, obj: Register, objtype: Type[Register]) -> RegField
test_class_dec.py:125: error: Missing positional argument "self" in call to "reg_func" of "Register"
test_class_dec.py:127: error: No overload variant of "__get__" of "FieldDescpr" matches argument types "None", "Type[BAZ]"
test_class_dec.py:127: note: Possible overload variants:
test_class_dec.py:127: note:     def __get__(self, obj: None, objtype: None) -> FieldDescpr
test_class_dec.py:127: note:     def __get__(self, obj: Register, objtype: Type[Register]) -> RegField

Your Environment

  • Python 3.10.4
  • mypy 0.981 (compiled: no)

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 mypy en el ejemplo test_class_dec.py del gist y compara la clase BAZ decorada y anidada con BAR y BOO. Sigue cómo mypy gestiona los tipos de descriptor y decorator, y confirma después que el fix elimina los errores informados sin alterar el comportamiento mostrado en tiempo de ejecución.

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

Evaluación

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

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.