]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-41006: collections imports lazily heap (GH-20940)
authorVictor Stinner <vstinner@python.org>
Wed, 17 Jun 2020 17:10:47 +0000 (19:10 +0200)
committerGitHub <noreply@github.com>
Wed, 17 Jun 2020 17:10:47 +0000 (19:10 +0200)
The collections module now imports lazily the heapq modules in the
Counter.most_common() method to speedup Python startup time.

Lib/collections/__init__.py

index 42d0ec777c3f75b3b4adce02fe71f5a560fa6969..5d75501645fc4a7ec8e7c0cdadea7a8a0f9bd12f 100644 (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.