Skip to content

mypy throws error using min with a key function specified #1150

New issue

Have a question about this project? No Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “No Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? No Sign in to your account

Closed
timabbott opened this issue Jan 25, 2016 · 9 comments
Closed

mypy throws error using min with a key function specified #1150

timabbott opened this issue Jan 25, 2016 · 9 comments
Labels
bug mypy got something wrong

Comments

@timabbott
Copy link

Reproducer: min([1, 2], key = lambda x: -x)

@JukkaL JukkaL added the bug mypy got something wrong label Jan 25, 2016
@JukkaL
Copy link
Collaborator

JukkaL commented Jan 25, 2016

The stub handles this case, but mypy complains because it doesn't consider keyword argument names when picking an overload variant. This is a vaguely known issue that has been around for a long time, but I can't find a duplicate tracker issue.

@timabbott
Copy link
Author

Looks like this also affects sorted; reproducer:
sorted([{'name': 'test'}], key=lambda x: x['name'])

@gvanrossum
Copy link
Member

gvanrossum commented Jan 25, 2016 via email

@gvanrossum
Copy link
Member

The PY3 overloads for min() currently look like this:

@overload
def min(arg1: _T, arg2: _T, *args: _T) -> _T: ...
@overload
def min(iterable: Iterable[_T], key: Callable[[_T], Any] = None) -> _T: ...

(max() and PY2 are similar.)
I can make all cases work (I think) by swapping the two and adding the key: to the one that's currently missing it, giving this:

@overload
def min(iterable: Iterable[_T], key: Callable[[_T], Any] = None) -> _T: ...
@overload
def min(arg1: _T, arg2: _T, *args: _T, key: Callable[[_T], Any] = None) -> _T: ...

My tests are as follows:

assert min(1, 2) == 1
assert min(1, 2, key=lambda x: -x) == 2
assert min([1, 2]) == 1
assert min([1, 2], key=lambda x: -x) == 2

Jukka, are you okay if I commit that to typeshed?

@gvanrossum
Copy link
Member

Jukka, can you look at python/typeshed#58 ? It fixes the issue for me.

@timabbott
Copy link
Author

Ok created #1160 for the sorted issue

@gvanrossum
Copy link
Member

Closed by 6a47ac7.

@gvanrossum
Copy link
Member

Sorry, I'm going to have to revert the fix, I think Jukka's right and this requires a fix to mypy.
What broke with the "fix" was max(a, 10) where the type of a is Any.

@JukkaL JukkaL reopened this Jan 28, 2016
@JukkaL
Copy link
Collaborator

JukkaL commented Jan 28, 2016

I'm looking at fixing overload resolution.

No Sign up for free to join this conversation on GitHub. Already have an account? No Sign in to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

3 participants