Skip to content

mypy failed to evaluate TypeVar in function parameter #18816

Open
@KaitoHH

Description

@KaitoHH

Bug Report

mypy cannot infer typevar which is defined as the function parameter, even though it could be evaluated from the following decorated function

To Reproduce

import functools
import time
from typing import Callable, ParamSpec, TypeVar, Any

_P = ParamSpec("_P")
_T = TypeVar("_T")


def retry(
    max_retry: int = 3,
    interval: int = 1,
    should_retry: Callable[[_T], bool] | None = None,
) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]:
    def decorator(func: Callable[_P, _T]) -> Callable[_P, _T]:
        @functools.wraps(func)
        def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _T:
            failed_cnt = 0
            while True:
                try:
                    result = func(*args, **kwargs)
                    if should_retry is not None and should_retry(result):
                        raise ValueError("result is not expected")
                    return result
                except Exception as e:
                    failed_cnt += 1
                    if failed_cnt > max_retry:
                        e.add_note(f"Retry {max_retry} times failed.")
                        raise e
                    time.sleep(interval)

        return wrapper

    return decorator

@retry() # Argument 1 has incompatible type "Callable[[int], int]"; expected "Callable[[int], Never]"
def f(x: int) -> int:
    return x


if __name__ == "__main__":
    f(1)

Expected Behavior

no error

Actual Behavior

Argument 1 has incompatible type "Callable[[int], int]"; expected "Callable[[int], Never]"

Your Environment

  • Mypy version used: 1.15.0
  • Python version used: 3.12

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions