Open
Description
Mypy unsoundly accepts a generic function with a generic mutable default parameter value. This value is evaluated once at runtime, but can be referred to with multiple incompatible types, breaking type safety.
from typing import TypeVar
T = TypeVar("T")
def f(x: T, y: list[T] = []) -> list[T]:
return y
y_strs: list[str] = f("a")
y_ints: list[int] = f(4)
# Uh oh, y_strs and y_ints refer to the same list with incompatible types
y_strs.append("b")
print(y_ints[0] + 6) # oops
(This is a sort of converse to #3737, where the complaint is that mypy fails to accept a generic function with a non-generic default parameter value. It further supports my claim that default parameter values should not be generalized to the generic type of the parameter at function definition time.)
Related: