Field of union needs to be different type when reading vs setting
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
Mypy appears to infer that the type of a field of a variable that is typed as a union is a single type whether that field is being read or updated. The type correct when reading the field (union of the types of the fields) , but not correct when setting as it does not enforce that the value being assigned needs to be valid for both of the types in the union (intersection of the types of the fields).
To Reproduce
class Foo:
a: int
class Bar:
a: str
either: Foo | Bar
either.a = 1 # No error, despite not being valid for Bar
More detailed example: https://mypy-play.net/?mypy=latest&python=3.12&gist=bf74f1ba35979f10b1878b2e1abca865
Expected Behavior
Mypy should report the assignment as an error if it does not work with all the types in the union.
Actual Behavior
No error, despite the assignment allowing a field of type str to be an int
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 Foo/Bar example and the linked mypy-play reproduction to compare field reads with assignments on a union. Trace the relevant union attribute assignment checking, then confirm the issue is resolved when assignments are accepted only if valid for every union member and the reported example produces an error.
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
- Mostly clear
- Newbie friendliness
- 35/100