From: Raymond Hettinger Date: Tue, 3 Dec 2024 02:45:36 +0000 (-0600) Subject: Speed-up lazy heapq import in collections (gh-127538) X-Git-Tag: v3.14.0a3~143 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=dffb90911a585a0921664c8b1c229d0883e65ee7;p=thirdparty%2FPython%2Fcpython.git Speed-up lazy heapq import in collections (gh-127538) --- diff --git a/Lib/collections/__init__.py b/Lib/collections/__init__.py index d688141f9b18..78229ac54b80 100644 --- a/Lib/collections/__init__.py +++ b/Lib/collections/__init__.py @@ -59,6 +59,8 @@ try: except ImportError: pass +heapq = None # Lazily imported + ################################################################################ ### OrderedDict @@ -633,7 +635,10 @@ class Counter(dict): return sorted(self.items(), key=_itemgetter(1), reverse=True) # Lazy import to speedup Python startup time - import heapq + global heapq + if heapq is None: + import heapq + return heapq.nlargest(n, self.items(), key=_itemgetter(1)) def elements(self):