Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Possible regression when narrowing using isinstance #16462

Open
cmeyer opened this issue Nov 11, 2023 · 2 comments
Open

Possible regression when narrowing using isinstance #16462

cmeyer opened this issue Nov 11, 2023 · 2 comments
Assignees
Labels
bug mypy got something wrong

Comments

@cmeyer
Copy link

cmeyer commented Nov 11, 2023

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

@cmeyer cmeyer added the bug mypy got something wrong label Nov 11, 2023
@ilevkivskyi
Copy link
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.

@cmeyer
Copy link
Author

cmeyer commented Nov 11, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

2 participants