Issue 20407: heapq.nsmallest and heapq.nlargest don't accept a "key" parameter (original) (raw)

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: http://docs.python.org/3.3/library/heapq.html#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/heapq.py 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 heapq.py. Tricky!
History
Date User Action Args
2022-04-11 14:57:57 admin set github: 64606
2014-01-27 15:12:38 georg.brandl set messages: +
2014-01-27 15:09:50 rhettinger set status: open -> closedpriority: low -> normalassignee: rhettingernosy: + rhettingermessages: + resolution: not a bug
2014-01-27 13:38:40 georg.brandl set messages: +
2014-01-27 11:53:04 larry set nosy: + georg.brandl
2014-01-27 11:51:33 larry create