Subclass attribute type narrowing on assignment
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Documentation
Consider this code snippet:
from typing import Iterable
class A:
attr1: Iterable[str] # narrows to different type, specific number of elements.
attr2: tuple[str, ...] # narrows to specific number of elements
class B(A):
attr1 = "a", "b"
attr2 = "a", "b", "c"
reveal_type(B.attr1)
reveal_type(B.attr2)
With this, mypy will tell us that Revealed type is "Tuple[builtins.str, builtins.str]" and Revealed type is "Tuple[builtins.str, builtins.str, builtins.str]" for attr1 and attr2 respectively. I can't find this behaviour documented, neither in PEP484, nor the Python typing docs, nor mypy docs. I don't even know where this should be documented best. But for what it's worth, I asked pylance, which says Type of "B.attr1" is "tuple[str, ...]" and Type of "B.attr2" is "tuple[str, ...]". Which tells me that the intended behaviour isn't clear for other people, too.
Note: I'm aware that this may be a bug report instead. But I rather err on the side of this not being clearly specified yet than being incorrectly implemented.
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 reading PEP 484, the Python typing documentation, and the mypy documentation for the subclass assignments shown. Compare mypy's revealed types with Pylance's reports, then document the intended behavior or clarify whether the discrepancy should be treated as a bug.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 35/100