Mypy: Mapping to abs doesn't work

Created on 18 Apr 2019  路  5Comments  路  Source: python/mypy

I first encountered this issue with Python 3.6.7 and mypy 0.560 from my distribution's repositories, but it also occurs on Python 3.7 and mypy 0.701, and the current master.

This is the code in question:

map(abs, [1])

It works, of course. But running mypy on it raises an error:

test.py:2: error: Argument 1 to "map" has incompatible type "Callable[[SupportsAbs[_T]], _T]"; expected "Callable[[int], _T]"

If I change it to the following code, there are no errors:

map(lambda x: abs(x), [1])

(This is a minimal example, my original code was something like sum(map(abs, list_of_floats)).)

So, what's the problem here? int and float have .__abs__.

bug priority-0-high topic-type-variables

Most helpful comment

I was able to recreate it with something more generic -

from typing import TypeVar, Callable

T = TypeVar("T")
S = TypeVar("S")

def f(x: T) -> T:
    return x

def g(f: Callable[[T], S], x: T) -> S:
    return f(x)

g(f, 1)

Output:
error: Argument 1 to "g" has incompatible type "Callable[[T], T]"; expected "Callable[[int], T]"

All 5 comments

This looks like a type inference bug. It is hard to tell what exactly went wrong, but mypy complains because it wanted SupportsAbs[int], not SupportsAbs[_T].

This happened again in https://github.com/python/mypy/issues/6703, and looks like a fundamental issue, so raising priority to high.

I was able to recreate it with something more generic -

from typing import TypeVar, Callable

T = TypeVar("T")
S = TypeVar("S")

def f(x: T) -> T:
    return x

def g(f: Callable[[T], S], x: T) -> S:
    return f(x)

g(f, 1)

Output:
error: Argument 1 to "g" has incompatible type "Callable[[T], T]"; expected "Callable[[int], T]"

I was able to recreate it with something more generic

Yes, this is a nice repro.

For future reference, there is a similar example in https://github.com/python/mypy/issues/4584

This is essentially the same as https://github.com/python/mypy/issues/1317, but I would like to keep this open as an important use case.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Stiivi picture Stiivi  路  3Comments

squarewave24 picture squarewave24  路  3Comments

takeda picture takeda  路  3Comments

Stiivi picture Stiivi  路  3Comments

mplanchard picture mplanchard  路  3Comments