python / python/mypy

mypy failed to return correct overloaded func type when decorate func accepts more than one parameter

Ouverte
#18,167 2 commentaires 0 réactions 0 personnes assignées Voir sur GitHub

Personne n'a encore pris cette issue.

bug topic-overloads topic-paramspec
Langage dominant
Python
Étoiles
20.6k
Forks
3.3k
Métriques de merge des PR
Métriques de PR en attente

Description

Bug Report

mypy failed to return the correct overloaded func type when decorate func accepts more than one parameter.

To Reproduce

from functools import wraps
from typing import overload, Any, TypeVar, Callable, Type

from typing_extensions import ParamSpec, reveal_type


@overload
def foo(a: str, /) -> str:
    pass


@overload
def foo(a: int, /) -> int:
    pass


def foo(a: Any) -> Any:
    return a


P = ParamSpec("P")
T = TypeVar("T")
R = TypeVar("R")


def forbid_return_type(
    func: Callable[P, T],
    tp: Type[Any],
    /,
) -> Callable[P, T]:
    @wraps(func)
    def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
        result = func(*args, **kwargs)

        if isinstance(result, tp):
            raise TypeError(f"Return type {tp} is forbidden")

        return result

    return wrapper


foo_as_int = forbid_return_type(foo, str)

reveal_type(foo_as_int(1))
reveal_type(foo_as_int("1"))

Expected Behavior

note: Revealed type is "builtins.int"
note: Revealed type is "builtins.str"

Actual Behavior

note: Revealed type is "builtins.str"
error: Argument 1 has incompatible type "int"; expected "str"  [arg-type]
note: Revealed type is "builtins.str"

Your Environment

  • Mypy version used: mypy 1.14.0+dev
  • Mypy command-line flags: -
  • Mypy configuration options from mypy.ini (and other config files): -
  • Python version used: 3.8.19

Both codes bellow work as expected:

from functools import wraps
from typing import overload, Any, TypeVar, Callable

from typing_extensions import ParamSpec, reveal_type


@overload
def foo(a: str, /) -> str:
    pass


@overload
def foo(a: int, /) -> int:
    pass


def foo(a: Any) -> Any:
    return a


P = ParamSpec("P")
T = TypeVar("T")
R = TypeVar("R")


def forbid_return_type(
    func: Callable[P, T],
) -> Callable[P, T]:
    @wraps(func)
    def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
        result = func(*args, **kwargs)
        return result

    return wrapper


foo_as_int = forbid_return_type(foo)

reveal_type(foo_as_int(1))
reveal_type(foo_as_int("1"))
from functools import wraps
from typing import Any, TypeVar, Callable, Type, Union

from typing_extensions import ParamSpec, reveal_type


def foo(a: Union[int, str]) -> Union[int, str]:
    return a


P = ParamSpec("P")
T = TypeVar("T")
R = TypeVar("R")


def forbid_return_type(
    func: Callable[P, T],
    tp: Type[Any],
    /,
) -> Callable[P, T]:
    @wraps(func)
    def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
        result = func(*args, **kwargs)

        if isinstance(result, tp):
            raise TypeError(f"Return type {tp} is forbidden")

        return result

    return wrapper


foo_as_int = forbid_return_type(foo, str)

reveal_type(foo_as_int(1))
reveal_type(foo_as_int("1"))

So it's not working only when the function accepts an overloaded function and another argument.

I checked with pyright and it correctly handles code.

  /Users/yuriikarabas/projects/mypy/temp.py:45:13 - information: Type of "foo_as_int(1)" is "int"
  /Users/yuriikarabas/projects/mypy/temp.py:46:13 - information: Type of "foo_as_int("1")" is "str"
0 errors, 0 warnings, 2 informations 

Guide de contribution

Ouvrir le guide de contribution

Par où commencer

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. Ouvrez une pull request qui référence le numéro de l'issue.

Piste de recherche

Commencez par exécuter le reproducteur minimal avec mypy et comparez les types révélés à la sortie attendue. Suivez l’inférence des overloads et de ParamSpec pour la fonction décorée lorsque le décorateur reçoit son deuxième argument. C’est terminé lorsque le reproducteur révèle int pour foo_as_int(1) et str pour foo_as_int("1") sans erreur de type d’argument.

Rédigé par le modèle d'indexation à partir du texte de l'issue.

Évaluation

Stack technique
python
Domaine
devtools
Type d'issue
Bug
Difficulté
4/5
Temps estimé
3-5 jours
Activité
À l'abandon
Clarté
Plutôt claire
Accessibilité débutants
35/100

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.