python / python/mypy

Default values for generic attributes are unsafe

Open
#5,703 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug priority-2-low topic-type-variables
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the issue with the Python example in the report and inspect mypy's handling of generic attributes and default values. Determine the intended diagnostic for the shared mutable default, then add regression coverage showing that generic specializations cannot unsafely share it and verify the existing example is rejected.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers, devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.