Floats interpreted as int?

Hi,

Here I see that both floats and complex numbers are interpreted as int. That does not seem like a good idea. It is not very intuitive here:

from pydantic import RootModel

class MVAWp(RootModel[float | tuple[float,float]]):
    def __str__(self):
        if isinstance(self.root, float):
            return f'{self.root:.3f}'

        low, high = self.root
        return f'{low:.3f}-{high:.3f}'

fval : float = 3.

val = MVAWp(fval)
print(val)

val = MVAWp((fval, fval))
print(val)

I would always get a type annotation error:

The only way I see to make this work safely is to create my own float type.

You can use numbers.Real in place of float for the purpose.

Which typechecker are you using? It looks like mypy does not produce an error, while pyright does for the code snippet you shared. I interpret the doc section linked to just refer to function arguments, not any variable marked as float (e.g., foo(1) is acceptable for def foo(x: float): ...).

Then, I’d view mypy’s behavior as more correct, while pyright is guarding against a potential pitfall. I don’t know how pydantic works under the hood, but MVAWp(1) works even though isinstance(1, float) == False.

Ben’s suggestion still produces type errors (seems like a bug though), but outside of pydantic numbers.Real would guard against passing ints vs floats.

Hi,

I am using pyright and it does produce an error for me, the maintainer himself acknowledges it here