bpo-41006: collections imports lazily heap (GH-20940)

The collections module now imports lazily the heapq modules in the
Counter.most_common() method to speedup Python startup time.
This commit is contained in:
Victor Stinner 2020-06-17 19:10:47 +02:00 committed by GitHub
parent bb6ec14479
commit 7824cc05bf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 4 additions and 2 deletions

View File

@ -27,7 +27,6 @@ __all__ = [
]
import _collections_abc
import heapq as _heapq
import sys as _sys
from itertools import chain as _chain
@ -608,7 +607,10 @@ class Counter(dict):
# Emulate Bag.sortedByCount from Smalltalk
if n is None:
return sorted(self.items(), key=_itemgetter(1), reverse=True)
return _heapq.nlargest(n, self.items(), key=_itemgetter(1))
# Lazy import to speedup Python startup time
import heapq
return heapq.nlargest(n, self.items(), key=_itemgetter(1))
def elements(self):
'''Iterator over elements repeating each as many times as its count.