Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unsoundly accepts generic function with generic mutable default parameter #13054

Open
andersk opened this issue Jul 2, 2022 · 1 comment
Open
Labels
bug mypy got something wrong topic-type-variables

Comments

@andersk
Copy link
Contributor

andersk commented Jul 2, 2022

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

mypy Playground link

(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:

@andersk andersk added the bug mypy got something wrong label Jul 2, 2022
@AlexWaygood
Copy link
Member

This is a very similar issue to #5703.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-type-variables
Projects
None yet
Development

No branches or pull requests

3 participants