Skip to content

bpo-34149: Behavior of the min/max with key=None #8328

New issue

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

By clicking “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? Sign in to your account

Merged
merged 3 commits into from
Jul 24, 2018
Merged

bpo-34149: Behavior of the min/max with key=None #8328

merged 3 commits into from
Jul 24, 2018

Conversation

Amper
Copy link
Contributor

@Amper Amper commented Jul 18, 2018

https://bugs.python.org/issue34149

I was faced with the fact that the behavior of the functions "min"/"max" and "sorted" is a little different.

For example, this code works fine:

>>> sorted([3, 2, 1], key=None)
[1, 2, 3]

But the same example for "min" and "max" doesn't work:

>>> min([3, 2, 1], key=None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable

That is why the heapq library has this code:

...
def nsmallest(n, iterable, key=None):
    ...
        if key is None:
            result = min(it, default=sentinel)
        else:
            result = min(it, default=sentinel, key=key)
    ...

At the same time, there are many places where such checks are not performed for the "sorted" function. I think the behavior of the "min" / "max" / "sorted" functions should be unified. That is, they should work as if "None" is the default value for "key".

https://bugs.python.org/issue34149

@rhettinger
Copy link
Contributor

rhettinger commented Jul 21, 2018

Amper, please add a NEWS entry using blurb.py (see the devguide for details).

If Serhiy don't feel strongly enough about this to reject this PR, I'll accept and apply it shortly. I'm persuaded by your idea that min(), max(), nsmallest(), nlargest(), sorted(), and itertools.groupby() should ideally have the same API for key functions. Syncing of those APIs would be a minor improvement. As Serhiy pointed out, this does complicate the type signature a bit, but that is of small concern given that the other four functions listed have already gone down this path.

@rhettinger
Copy link
Contributor

This also needs a documentation update including a versionchanged directive.

@Amper
Copy link
Contributor Author

Amper commented Jul 22, 2018

@rhettinger, ok, i have no experience in this, but I'll try to do it tomorrow

@Amper
Copy link
Contributor Author

Amper commented Jul 23, 2018

@rhettinger Is everything done right?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants