mypy: Why is “int” a subtype of “float”?

前端 未结 2 1137
慢半拍i
慢半拍i 2020-12-16 19:43

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

2条回答
  •  执念已碎
    2020-12-16 20:19

    'Why does "mypy" consider "int" as a subtype of "float"?'

    Because practicality has so far been considered to beat purity here. This is not to say that one could not propose that typing define a Scalar type that would include ints and floats but only be valid for arithmetic operations.

    Note that int / int was changed in 3.0 so that float(int / int) == float(int) / float(int), to make int and float arithmetic consistent for equal int and float values.

    Note also that a type-check passing does not mean no runtime errors: division by zero and overflow are still possible, as well as many others.

提交回复
热议问题