Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Unsoundly accepts generic function with generic mutable default parameter #13054

Description

@andersk

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:

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions