Skip to content

Possible regression when narrowing using isinstance #16462

Closed

Description

@cmeyer

Bug Report

Type narrowing using isinstance with 1.7 behaves differently from 1.6 for seemingly valid code.

To Reproduce

import typing

class A:
    def write(self) -> str:
        return "A"

    # succeeds
    def eq1(self, other: typing.Any) -> bool:
        if other:
            if isinstance(other, self.__class__):
                return self.write() == other.write()
        return False

    # fails
    def eq2(self, other: typing.Any) -> bool:
        if other and isinstance(other, self.__class__):
            return self.write() == other.write()
        return False

Expected Behavior

The eq1 and eq2 should both be valid code. eq2 fails under 1.7 but succeeded under 1.6.

Actual Behavior

file.py:15: error: Returning Any from function declared to return "bool"  [no-any-return]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.7.0
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
# Global options:

[mypy]
ignore_missing_imports = True
follow_imports = silent
strict = True
  • Python version used:

Python 3.12 macos-arm64

Activity

  1. ilevkivskyi commented on Nov 11, 2023

    @ilevkivskyi
    Member

    Yeah, most likely I did this. Any with type narrowing works quite arbitrary (and it was never really consistent). It actually works for flipped order (i.e. if isinstance(other, self.__class__) and other: ...). I will check if it is easy to make it more consistent (or at least return the old behavior) without causing troubles in other places.

  2. cmeyer commented on Nov 11, 2023

    @cmeyer
    Author

    I'm already changing my code to use only the isinstance check. The first clause (other) is redundant since None cannot ever pass the isinstance check anyway. Thanks for all of your other work.

  3. self-assigned this
    on Nov 13, 2023
  4. added a commit that references this issue on Apr 9, 2026
    ef28d9c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugmypy got something wrong

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions