MyPy treats initialization of a variable as an assignment for variance checks for complex dictionary.
Open
Nobody has claimed this yet.
bug
topic-type-context
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
The problem is that when initializing a variable from a dictionary expression it treats the type as invariant, but in the case of initialialization, it is covariant.
Example:
CODES = {
"a": "b",
"c": "d",
"e": "f",
}
# MyPy rejects this
PATTERNS: dict[str, tuple[str | None, str | None]] = {
"1" + k: ((v + "1" if v else None), "x")
for (k, v) in CODES.items()
} | {
"2" + k: ((v + "2" if v else None), "x")
for (k, v) in CODES.items()
}
# But is OK with this:
X: str | None = "x"
PATTERNS2: dict[str, tuple[str | None, str | None]] = {
"1" + k: ((v + "1" if v else None), X)
for (k, v) in CODES.items()
} | {
"1" + k: ((v + "1" if v else None), X)
for (k, v) in CODES.items()
}
Both patterns should be OK.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by running the provided MyPy example and compare the diagnostics for PATTERNS and PATTERNS2. Trace the type-checking path for dictionary expressions combined with annotated initialization and variance checks. Add a regression test covering the example; done means both patterns are accepted without weakening unrelated variance checking.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 38/100