Skip to content

Default values for generic attributes are unsafe #5703

Open

Description

@ilevkivskyi

Currently mypy accepts this unsafe code:

from typing import Generic, TypeVar, List
  
T = TypeVar('T')

class B(Generic[T]):
    x: List[T] = []

class C1(B[int]):
    pass

class C2(B[str]):
    pass

C1().x.append(42)
C2().x.append('Hm...')

A potential solution would be to disallow all default values for generic attributes except None. This is however a low priority, since it is a false negative, and a rare corner case.

Activity

  1. andersk commented on Jul 2, 2022

    @andersk
    Contributor

    Same issue as #11538.

    We don’t need to go so far as disallowing all defaults other than None. Any default value is fine as long as the default value has a type that can be written without T. For example:

    • x: Sequence[T] = [] is fine because [] has type Sequence[Never], which can be written without T, but is convertible to Sequence[T] by covariance. That is, a single [] may simultaneously have type Sequence[T] for all T.
    • x: List[T] = [] must be disallowed; no single [] may simultaneously have type List[T] for all T.
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