python / python/mypy

Decorator confused by keyword-only parameter with Union, erroneously expects `<nothing>`, but only in some cases?

Abierto
#12,103 2 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
Merge medio
1 d 18 h
PR fusionados (30 d)
54

Descripción

I am trying to write a decorator function that takes optional keyword arguments. I.e., it can be called like …

@decr
def func(…):
  …

… or …

@decr(param=val)
def func(…):
  …

I have gotten myself into a pickle with a variation of the second.

# test_case.py
from __future__ import annotations
from functools import wraps
from typing import Callable, Optional, Protocol, TypeVar, Union, overload

_ReturnsIntT = Callable[..., int]
_SubjectT = TypeVar("_SubjectT", bound=_ReturnsIntT)

class _DecoratedT(Protocol):
    def __call__(self, *args: int, join_str="", **kw: int) -> str:
        ...

@overload
def strintify(
    *,
    addtl: Union[int, _SubjectT] = 0,
) -> Callable[[_SubjectT], _DecoratedT]:
    ...

@overload
def strintify(
    f: _SubjectT,
) -> _DecoratedT:
    ...

def strintify(
    f: Optional[_SubjectT] = None,
    *,
    addtl: Union[int, _SubjectT] = 0,
) -> Union[Callable[[_SubjectT], _DecoratedT], _DecoratedT]:
    assert callable(f) or f is None

    def _decorator(f):
        @wraps(f)
        def _f(*args: int, join_str="", **kw: int) -> str:
            res = [f(*args, **kw)]
            if isinstance(addtl, int):
                res[0] += addtl
            else:
                res.append(addtl(*args, **kw))
            return join_str.join(str(i) for i in res)

        return _f
    return _decorator(f) if callable(f) else _decorator

@strintify  # <-- this is fine
def func1(a: int, b: int, c: int) -> int:
    return a**3 + b**2 + c

print(func1(3, 2, 1))  # prints 32
print(func1(3, 2, 1, join_str="|"))  # prints 32

@strintify(addtl=1)  # <-- #@#@#@#@# ERRORS HERE #@#@#@#@#
def func2(a: int, b: int, c: int) -> int:
    return a**3 + b**2 + c

print(func2(3, 2, 1))  # prints 33
print(func2(3, 2, 1, join_str="|"))  # prints 33

@strintify(addtl=lambda a, b, c: c**3 + b**2 + a)  # <-- this is fine
def func3(a: int, b: int, c: int) -> int:
    return a**3 + b**2 + c

print(func3(3, 2, 1))  # prints 328
print(func3(3, 2, 1, join_str="|"))  # prints 32|8

Type-checking that gives:

% mypy --config=/dev/null test_case.py
/dev/null: No [mypy] section in config file
test_case.py:53: error: Argument 1 has incompatible type "Callable[[int, int, int], int]"; expected <nothing>
Found 1 error in 1 file (checked 1 source file)
% mypy --version
mypy 0.931
% python --version
Python 3.9.10

Apologies for the long use case, I haven't been able to figure out how to reduce it yet.

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

Comienza con el ejemplo autocontenido de test_case.py y ejecuta mypy 0.931 usando el comando mostrado para reproducir el error en el caso @strintify(addtl=1). Traza cómo se analiza la sobrecarga de Union exclusiva para palabras clave y añade una prueba de regresión que muestre que func2 se acepta, mientras que los casos existentes func1 y func3 siguen siendo válidos.

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
4/5
Tiempo estimado
3-5 días
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.