Skip to content

Commit 073d935

Browse files
vstinnerarun-mani-j
authored andcommitted
bpo-41006: collections imports lazily heap (pythonGH-20940)
The collections module now imports lazily the heapq modules in the Counter.most_common() method to speedup Python startup time.
1 parent 55bec89 commit 073d935

File tree

1 file changed

+4
-2
lines changed

1 file changed

+4
-2
lines changed

Lib/collections/__init__.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@
2727
]
2828

2929
import _collections_abc
30-
import heapq as _heapq
3130
import sys as _sys
3231

3332
from itertools import chain as _chain
@@ -608,7 +607,10 @@ def most_common(self, n=None):
608607
# Emulate Bag.sortedByCount from Smalltalk
609608
if n is None:
610609
return sorted(self.items(), key=_itemgetter(1), reverse=True)
611-
return _heapq.nlargest(n, self.items(), key=_itemgetter(1))
610+
611+
# Lazy import to speedup Python startup time
612+
import heapq
613+
return heapq.nlargest(n, self.items(), key=_itemgetter(1))
612614

613615
def elements(self):
614616
'''Iterator over elements repeating each as many times as its count.

0 commit comments

Comments
 (0)