mypy icon indicating copy to clipboard operation
mypy copied to clipboard

Calling float.__add__ with an integer as first argument is valid

Open malbarbo opened this issue 1 year ago • 3 comments

Calling float.__add__ with an integer as first argument is valid.

Example

float.__add__(1, 2)

Expected Behavior

Considering that the code fails at runtime, mypy should not accept this code.

Environment

  • Mypy version used: 1.9
  • Python version used: 3.11.2

malbarbo avatar Apr 02 '24 22:04 malbarbo

I would like to work on this with a group for a college software engineering class.

kr321 avatar Apr 08 '24 14:04 kr321

This is probably accepted because of the special case where int is treated like a subtype of float (https://typing.readthedocs.io/en/latest/spec/special-types.html#special-cases-for-float-and-complex).

There are ways to implement this special case that would not have this issue, but such changes may have complicated consequences.

JelleZijlstra avatar Apr 08 '24 17:04 JelleZijlstra

I understand https://typing.readthedocs.io/en/latest/spec/special-types.html#special-cases-for-float-and-complex) is useful for legacy code, but I think there should be a "strict" flag to disable it. In my case, since we interact with another language (julia), we need to control the exact types.

A case where this "allowance" is weird is when storing the value. Mypy does not report any error, but the dataclass field does not contain the declared type.

from dataclasses import dataclass


@dataclass
class C:
    f: float = 0


print(type(C().f))
c = C(f=4)
print(type(c.f))

python prints this

<class 'int'>
<class 'int'>

dpinol avatar Jun 20 '24 10:06 dpinol