Why does Mypy Consider int
a Subtype of float
?
Mypy considers int
a subtype of float
because it allows passing an int
argument for a float
parameter. This code example demonstrates this behavior:
def f(x : float) -> bool:
return x.is_integer()
print(f(123.0))
print(f(123))
Mypy accepts this code with no issues:
(3.8.1) myhost% mypy test.py
Success: no issues found in 1 source file
However, this does not guarantee that there will be no errors at runtime because float
has methods that int
does not have. For example, this code produces an error at runtime:
(3.8.1) myhost% python test.py
True
Traceback (most recent call last):
File "test.py", line 5, in <module>
print(f(123))
File "test.py", line 2, in f
return x.is_integer()
AttributeError: 'int' object has no attribute 'is_integer'