top | item 43770363

(no title)

drumnerd | 10 months ago

0 can be inferred as a float too, so doesn’t it make sense to type numbers?

discuss

order

hk__2|10 months ago

Try:

    def f(i=0) -> None:
        reveal_type(i)
The inferred type is not `float` nor `int`, but `Any`. Mypy will happily let you call `f("some string")`.

mzl|10 months ago

How would a typing system know if the right type is `int` or `Optional[int]` or `Union[int, str]` or something else? The only right thing is to type the argument as `Any` in the absence of a type declaration.

rfoo|10 months ago

`Any` is the correct call.

It could be:

  def f(i=0) -> None:
    if i is None:
      do_something()
    else:
      do_something_else()
Yeah, I know it's retarded. I don't expect high quality code in a code base missing type annotation like that. Assuming `i` is `int` or `float` just makes incrementally adoption of a type checker harder.

veber-alex|10 months ago

That's a mypy issue.

Pyright correctly deduces the type as int.

In any case it's a bad example as function signatures should always be typed.

jsjohnst|10 months ago

So you want strong typing, but then are to lazy to properly type your function definitions?

porridgeraisin|10 months ago

I believe mypy infers i as an integer in i = 0. I remember I had to do i = 0.0 to make it accept i += someFloat later on. Or of course i:float = 0 but I preferred the former.

hk__2|10 months ago

Yes, but not in arguments:

    def f(i=0) -> None:
        j = i + 1
        k = 1
        reveal_type(i)
        reveal_type(j)
        reveal_type(k)
Output:

    Revealed type is "Any"
    Revealed type is "Any"
    Revealed type is "builtins.int"