This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Title: heapq.nsmallest and heapq.nlargest don't accept a "key" parameter
Type: behavior Stage: needs patch
Components: Library (Lib) Versions: Python 3.3, Python 3.4
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: rhettinger Nosy List: georg.brandl, larry, rhettinger
Priority: normal Keywords:

Created on 2014-01-27 11:51 by larry, last changed 2022-04-11 14:57 by admin. This issue is now closed.

Messages (4)
msg209435 - (view) Author: Larry Hastings (larry) * (Python committer) Date: 2014-01-27 11:51
The documentation for heapq.nsmallest and heapq.nlargest:

claim that they accept three arguments: n, iterable, and key=None.  In fact, the implementations of both these functions only accept two parameters: n and iterable.

I assume the right thing to do here is to remove the erroneous documentation, rather than implement this apparently-not-needed feature?
msg209442 - (view) Author: Georg Brandl (georg.brandl) * (Python committer) Date: 2014-01-27 13:38
Yes.  Probably someone wished they would implement it :)
msg209447 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2014-01-27 15:09
The docs are correct as-is.  This is a documented and tested behavior.

    >>> from heapq import nsmallest
    >>> list(nsmallest(3, ['larry', 'georg', 'raymond', 'guido', 'tim'], key=len))
    ['tim', 'larry', 'georg']

The C implementation doesn't have a key-argument.  That behavior gets added downstream in pure python in Lib/ which wraps the C-function and adds the additional behavior.
msg209448 - (view) Author: Georg Brandl (georg.brandl) * (Python committer) Date: 2014-01-27 15:12
I see, there are two "def nsmallest" in  Tricky!
Date User Action Args
2022-04-11 14:57:57adminsetgithub: 64606
2014-01-27 15:12:38georg.brandlsetmessages: + msg209448
2014-01-27 15:09:50rhettingersetstatus: open -> closed
priority: low -> normal

assignee: rhettinger

nosy: + rhettinger
messages: + msg209447
resolution: not a bug
2014-01-27 13:38:40georg.brandlsetmessages: + msg209442
2014-01-27 11:53:04larrysetnosy: + georg.brandl
2014-01-27 11:51:33larrycreate