How to fix lsp-pyright type hint errors; "int" is incompatible with "float"?

Viewed 32

Using this python example snippet below, I'm getting the error at the bottom

from typing import List
def foo(x:List[float]):
    pass

i=[3]
foo(i)

.

[Pyright] Argument of type "list[int]" cannot be assigned to parameter "x" of type "List[float]" in function "foo"
  TypeVar "_T@list" is invariant
    "int" is incompatible with "float" (5:4)

lsp-pyright: 20220614.1545


PEP 484 Type Hints specifically states that:

Rather than requiring that users write import numbers and then use numbers.Float etc., this PEP proposes a straightforward shortcut that is almost as effective: when an argument is annotated as having type float, an argument of type int is acceptable; similar, for an argument annotated as having type complex, arguments of type float or int are acceptable.

1 Answers

3 is an integer literal. While Python will generally transparently convert from integer to float if necessary, since you typed your code as float the typechecker wants a float.

Just use a float literal: 3.0, or just 3. (but it's a bit less readable).

PEP 484 Type Hints specifically states that:

Feel free to report the issue to pyright, possibly linked to / following up on issue 260.

However note that the argument is not annotated as having type float here, it's annotated as having type List[float], which is not quite the same situation (cf the variance section of PEP 484).

Related