Unsoundly accepts generic function with generic mutable default parameter
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
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:
- #11538
- #11585
- #3737
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the linked mypy Playground reproduction and compare it with related issues #3737, #11538, and #11585. Determine the expected treatment of generic mutable default parameters, then add coverage showing that the reported incompatible list aliases are not accepted while preserving the intended behavior for non-generic defaults.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 30/100