Skip to content

Default values for generic attributes are unsafe #5703

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

Open
ilevkivskyi opened this issue Oct 1, 2018 · 1 comment
Open

Default values for generic attributes are unsafe #5703

ilevkivskyi opened this issue Oct 1, 2018 · 1 comment
Labels

Comments

@ilevkivskyi
Copy link
Member

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.

@andersk
Copy link
Contributor

andersk commented Jul 2, 2022

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
Labels
Projects
None yet
Development

No branches or pull requests

2 participants