[Python] mypy: Why is "int" a subtype of "float"?

Discussão em 'Python' iniciado por Stack, Junho 14, 2025.

  1. Stack

    Stack Membro Participativo

    Why does "mypy" consider "int" as a subtype of "float"? A subtype shall support all methods of its supertype, but "float" has methods, which "int" does not support:

    test.py:

    def f(x : float) -> bool:
    return x.is_integer()

    print(f(123.0))
    print(f(123))


    The static type checker accepts passing an "int" argument for a "float" parameter:

    (3.8.1) myhost% mypy test.py
    Success: no issues found in 1 source file


    But this does not guarantee, that there are no errors 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'


    because "float" has additional methods, which "int" does not have.

    Continue reading...

Compartilhe esta Página