Skip to content

isinstance(X, float) wrongly consumes bool type #12114

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

Closed
tusharsadhwani opened this issue Feb 2, 2022 · 2 comments
Closed

isinstance(X, float) wrongly consumes bool type #12114

tusharsadhwani opened this issue Feb 2, 2022 · 2 comments
Labels
bug mypy got something wrong

Comments

@tusharsadhwani
Copy link
Contributor

In the following example, adding an unrelated isinstance check causes the code to raise an error.

To Reproduce

Code:

from typing import Union

def get_type_name(value: Union[bool, str]) -> str:
    if value is True:
        return "Boolean"
    if value is False:
        return "Boolean"
    return "String"

Mypy output:

$ mypy --strict testcode.py
Success: no issues found in 1 source file

Adding an isinstance(value, float) check:

from typing import Union

def get_type_name(value: Union[bool, str]) -> str:
    if isinstance(value, float):  # a completely unrelated check
        return "Number"

    if value is True:
        return "Boolean"
    if value is False:
        return "Boolean"

    return "String"

Mypy output:

$ mypy --strict testcode.py
testcode.py:5: error: Missing return statement
testcode.py:9: error: Non-overlapping identity check (left operand type: "str",
right operand type: "Literal[True]")
testcode.py:11: error: Non-overlapping identity check (left operand type: "str",
 right operand type: "Literal[False]")
Found 3 errors in 1 file (checked 1 source file)

Mypy says value is True and value is False are non overlapping checks, but it works:

$ python -i testcode.py
>>> get_type_name(5.0)
'Number'

Your Environment

  • Mypy version used: 0.931
  • Mypy command-line flags: --strict
  • Python version used: Python 3.9 and 3.10
  • Operating system and version: Linux, Pop!_OS 21.10
@tusharsadhwani tusharsadhwani added the bug mypy got something wrong label Feb 2, 2022
@JelleZijlstra
Copy link
Member

This is probably because bool is a subclass of int (in reality) and int is a subclass of float (in the type system).

@hauntsaninja
Copy link
Collaborator

mypy could maybe have an option to pretend that bool isn't a subclass of int, in which case this is a duplicate of #8363

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

3 participants