From 643e13e89abd73b75907dbd51c0f8914eb1b430e Mon Sep 17 00:00:00 2001 From: Victor Stinner Date: Wed, 17 Jun 2020 16:56:05 +0200 Subject: [PATCH] bpo-41006: collections imports lazily heap The collections module now import lazily the heapq modules in the Counter.most_common() method to speedup Python startup time. --- Lib/collections/__init__.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Lib/collections/__init__.py b/Lib/collections/__init__.py index 42d0ec777c3f75b..5d75501645fc4a7 100644 --- a/Lib/collections/__init__.py +++ b/Lib/collections/__init__.py @@ -27,7 +27,6 @@ ] import _collections_abc -import heapq as _heapq import sys as _sys from itertools import chain as _chain @@ -608,7 +607,10 @@ def most_common(self, n=None): # 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.