Skip to content

False positive in return type on a decorator factory whose results can decorate functions or coroutines #14776

@AndrewGibb

Description

@AndrewGibb

Bug Report

Mypy gives a false positive (with printed error messages indicating that matching types don't match) on the following code:

from typing import Callable, TypeVar, Coroutine, Any, Union, cast
import asyncio
import functools
import time

F = TypeVar('F', bound=Union[Callable[..., Any], Callable[..., Coroutine[Any, Any, Any]]])


def retry_forever() -> Callable[[F], F]:
    """This function returns a decorator which causes the decorated function or coroutine to
    retry repeatedly 
    :returns: A decorator
    """
    def __decorator(f: F) -> F:
        if asyncio.iscoroutinefunction(f):
            @functools.wraps(f)
            async def __inner(*args, **kwargs) -> Any:
                while True:
                    try:
                        f(*args, **kwargs)
                    except Exception:
                        await asyncio.sleep(1)
                    else:
                        break
            return __inner # error: Incompatible return value type (got "Callable[[VarArg(Any), KwArg(Any)], Coroutine[Any, Any, Any]]", expected "F")  [return-value]
        else:
            @functools.wraps(f)
            def __inner(*args, **kwargs) -> Any:
                while True:
                    try:
                        f(*args, **kwargs)
                    except Exception:
                        time.sleep(1)
                    else:
                        break
            return __inner # error: Incompatible return value type (got "Callable[[VarArg(Any), KwArg(Any)], Coroutine[Any, Any, Any]]", expected "F")  [return-value]
    return __decorator

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.10&gist=2819b5f48c59c1dde77fc502f34a023c

Expected Behavior
Since the error message reports types which match (modulo the mypy documentation here) this should pass type checking

Your Environment

  • Mypy version used: 1.0.0
  • Mypy command-line flags: None
  • Python version used: 3.10

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions