With a new syntax generic function, `T` cannot be used to set a default value to a parameter with `cast()` while `T` can be used for a parameter and return type
*Memo: mypy --strict test.py mypy 1.19.0 Python 3.14.0 Windows 11
With a new syntax generic function, T cannot be used to set a default value to a parameter with cast() while T can be used for a parameter and return type as shown below:
from typing import cast
# ↓ Error
def func[T](x: T = cast(T, 100)) -> T:
return x # ↑ No error # ↑ No error
error: Name "T" is not defined
If I don't use T with cast(), other error occurs as shown below:
# ↓↓↓ Error
def func[T](x: T = 100) -> T:
return x
error: Incompatible default for argument "x" (default has type "int", argument has type "T")
Your first snippet produces a runtime error. T is not in scope when defaults are evaluated. We could special-case that and allow quoted typevars there, but I don't think that's a good idea - T should only appear in type context, and default params are in value context, although the first arg of cast arguably belongs to the type land.
The second snippet is a duplicate of #3737.