Sumit
Sumit

Reputation: 2023

mypy giving error as incompatible type "Optional[int]"; expected "Union[SupportsFloat, str, bytes, bytearray]

I am getting an error while running mypy 0710 version in my code. I have made a small code snippet that is having an issue but not sure why this error is appearing

a = None
version = 2
if version == 2:
    a = 10
    #print("asdfgh")

if float(a) == 10:
    print("erty")

I am getting error when I run the code in mypy as

tests/test.py:8: error: Argument 1 to "float" has incompatible type "Optional[int]"; expected "Union[SupportsFloat, str, bytes, bytearray]"

Any help will be appreciated

Upvotes: 6

Views: 17228

Answers (1)

Michael0x2a
Michael0x2a

Reputation: 63978

The issue here is that mypy does not understand that your version variable will always be exactly 2 and therefore does not understand that your first if statement will always run.

And if the first if statement will only sometimes run, that means that a will sometimes never be assigned the value 10 and will remain None. That can potentially cause a type error later on: float(None) is not valid.

The easiest fixes are to either drop the unnecessary if-check:

a = None
version = 2
a = 10

if float(a) == 10:
    print("erty")

...or add in an "else" case that sets a to some other value if version is not equal to 2:

a = None
version = 2
if version == 2:
    a = 10
else:
    a = 99

if float(a) == 10:
    print("erty")

...or to assert that a will be of type int:

a = None
version = 2
if version == 2:
    a = 10

assert isinstance(a, int)

if float(a) == 10:
    print("erty")

I would personally recommend some variation of the first solution.

Upvotes: 11

Related Questions