Type narrowing fails for classes with custom `__getattr__`
Open
Nobody has claimed this yet.
bug
topic-type-narrowing
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
When a class has a custom __getattr__ with the return type of Any, the type narrowing of mypy does not work as expected in some cases.
To Reproduce
from typing import Any, Iterator, Union
from typing_extensions import reveal_type
class A(object):
def __getattr__(self, name: str) -> Any:
if name == "a":
return 1
else:
raise AttributeError
def func(a: Union[A, Iterator[A]]) -> None:
if isinstance(a, A):
reveal_type(a)
else:
reveal_type(a)
Expected Behavior
Revealed type is "A"
Revealed type is "typing.Iterator[A]"
Actual Behavior
Revealed type is "A"
Revealed type is "Union[A, typing.Iterator[A]]"
Your Environment
- Mypy version used: mypy 1.6.1
- Mypy command-line flags: No flags were used.
- Mypy configuration options from
mypy.ini(and other config files): None. - Python version used: Python 3.10.13
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 supplied Python reproducer with mypy 1.6.1 and comparing the revealed types with the expected output. Trace the type narrowing path for isinstance checks when the class defines getattr returning Any; done means the else branch narrows to Iterator[A] without regressing the first branch.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers, developer-experience
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 38/100