Skip to content

Type narrowing fails for classes with custom __getattr__ #16590

@Bobholamovic

Description

@Bobholamovic

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-type-narrowingConditional type narrowing / binder

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions