mypy error when mapping a list of values to float

Viewed 265

I am trying to evaluate the following statement using mypy:

a = [1,2,3]

b = map(float, a)

this returns the error

Argument 1 to "map" has incompatible type "Type[float]"; expected "Callable[[str], str]"

but at runtime this has no problem executing. What is the reason for this problem?

3 Answers

I wasn't able to replicate this either (Python Ver. 3.9.0, mypy Ver. 0.910) so first thing to try would be upgrading to latest versions.

Not quite the same issue, but these issues on the mypy github may be an interesting reference:

https://github.com/python/mypy/issues/6697 (Open)
https://github.com/python/mypy/issues/1855 (Closed)

Based on these, it looks like the following might pass without a mypy error:

b = map(lambda x: float(x), a)
a = [1,2,3]

b = map(lambda x: float(x), a)

The issue was related to using the same name for the result variable and the variable that map is applied to, I was doing something along the lines of

a = b.split()
a = list(map(lambda x: float(x),a))

which resulted in the error. Changing the variable name in the last line here resolved this problem.

Related